|
| 1 | +import { DeliveryClient } from '@kontent-ai/delivery-sdk'; |
| 2 | +import { signatureHelper } from '@kontent-ai/webhook-helper'; |
| 3 | +import { Handler } from "@netlify/functions"; |
| 4 | +import { |
| 5 | + IWebhookDeliveryData, |
| 6 | + IWebhookResponse |
| 7 | +} from "@kontent-ai/webhook-helper/dist/cjs/models/webhook-models.class.ts"; |
| 8 | + |
| 9 | +const CONFIG_DELIMITER = ","; |
| 10 | + |
| 11 | +export const handler: Handler = async (event) => { |
| 12 | + |
| 13 | + // Only receiving POST requests |
| 14 | + if (event.httpMethod !== "POST") { |
| 15 | + return { statusCode: 405, body: "Method Not Allowed" }; |
| 16 | + } |
| 17 | + |
| 18 | + if (!event.body) { |
| 19 | + return { statusCode: 400, body: "Missing body" }; |
| 20 | + } |
| 21 | + |
| 22 | + // Consistency check - make sure your netlify enrionment variable and your webhook secret matches |
| 23 | + if (!signatureHelper.isValidSignatureFromString(event.body, process.env.KONTENT_SECRET ?? '', event.headers['x-kc-signature'] ?? '')) { |
| 24 | + return { statusCode: 401, body: "Unauthorized" }; |
| 25 | + } |
| 26 | + |
| 27 | + const jsonBody: IWebhookResponse<IWebhookDeliveryData> = JSON.parse(event.body); |
| 28 | + const webhookMessage = jsonBody.message; |
| 29 | + const webhookData = jsonBody.data; |
| 30 | + |
| 31 | + // extracting projectId, operation & type from a webhook message |
| 32 | + const projectId = webhookMessage.project_id; |
| 33 | + const operation = webhookMessage.operation; |
| 34 | + const type = webhookMessage.type; |
| 35 | + |
| 36 | + // loading allowed operations and types from config |
| 37 | + const allowedOperations = process.env.ALLOWED_OPERATIONS?.split(CONFIG_DELIMITER) ?? []; |
| 38 | + const allowedTypes = process.env.ALLOWED_TYPES?.split(CONFIG_DELIMITER) ?? []; |
| 39 | + |
| 40 | + // if the method or type is not allowed abort |
| 41 | + if (projectId && allowedOperations.includes(operation) && allowedTypes.includes(type)) { |
| 42 | + return { statusCode: 200, body: '[]' }; |
| 43 | + } |
| 44 | + |
| 45 | + // download the affected items |
| 46 | + const deliveryClient = new DeliveryClient({ projectId }); |
| 47 | + const response = await Promise.all(webhookData.items.map(item => deliveryClient.item(item.codename).languageParameter(item.language).toPromise())); |
| 48 | + |
| 49 | + // print the affected content items into function log |
| 50 | + console.log(JSON.stringify(response)); |
| 51 | + |
| 52 | + return { |
| 53 | + statusCode: 200, |
| 54 | + body: `${JSON.stringify(response)}`, |
| 55 | + }; |
| 56 | +}; |
0 commit comments