feat: implement automatic webhook via Strapi lifecycle hooks

This commit is contained in:
echo 2026-02-27 17:11:04 +01:00
parent d7281024bf
commit 4f30542014
2 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,64 @@
/**
* Lifecycle hooks for Article content type
* Automatically notifies the backend when articles are published/updated/deleted
*/
export default {
async afterCreate(event) {
const { result } = event;
// Only notify if article is published
if (result.publishedAt) {
await notifyBackend('entry.publish', result);
}
},
async afterUpdate(event) {
const { result } = event;
if (result.publishedAt) {
await notifyBackend('entry.update', result);
} else {
await notifyBackend('entry.unpublish', result);
}
},
async afterDelete(event) {
const { result } = event;
await notifyBackend('entry.delete', result);
},
};
/**
* Notify backend via webhook
*/
async function notifyBackend(event: string, entry: any) {
const backendUrl = process.env.BACKEND_WEBHOOK_URL || 'http://backend:3000';
const webhookUrl = `${backendUrl}/api/v1/webhooks/strapi/article`;
const payload = {
event,
model: 'article',
entry: {
documentId: entry.documentId,
},
};
try {
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
console.error(`Webhook failed: ${response.status} ${response.statusText}`);
} else {
console.log(`✅ Webhook sent successfully: ${event} for article ${entry.documentId}`);
}
} catch (error) {
console.error(`Failed to notify backend: ${error.message}`);
}
}

View File

@ -131,6 +131,7 @@ services:
HOST: 0.0.0.0
PORT: 1337
PUBLIC_URL: https://cms.placebo.mk
BACKEND_WEBHOOK_URL: http://backend:3000
DATABASE_CLIENT: postgres
DATABASE_HOST: postgres-cms
DATABASE_PORT: '5432'