feat: implement automatic webhook via Strapi lifecycle hooks
This commit is contained in:
parent
d7281024bf
commit
4f30542014
64
cms/cms/src/api/article/content-types/article/lifecycles.ts
Normal file
64
cms/cms/src/api/article/content-types/article/lifecycles.ts
Normal 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}`);
|
||||
}
|
||||
}
|
||||
@ -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'
|
||||
|
||||
Loading…
Reference in New Issue
Block a user