Webhooks — HTTP callbacks for event notifications.
1class WebhookService {2 constructor(db) {3 this.db = db;4 }56 async register(event, url, secret) {7 return this.db.webhooks.create({ event, url, secret });8 }910 async trigger(event, payload) {11 const hooks = await this.db.webhooks.findByEvent(event);1213 await Promise.allSettled(14 hooks.map(hook => this.send(hook, payload))15 );16 }1718 async send(hook, payload) {19 const body = JSON.stringify(payload);20 const signature = crypto21 .createHmac("sha256", hook.secret)22 .update(body)23 .digest("hex");2425 const response = await fetch(hook.url, {26 method: "POST",27 headers: {28 "Content-Type": "application/json",29 "X-Webhook-Signature": signature,30 "X-Webhook-Event": hook.event,31 },32 body,33 });3435 if (!response.ok) {36 throw new Error(`Webhook failed: ${response.status}`);37 }38 }39}4041// Usage42await webhookService.trigger("order.created", {43 orderId: 123,44 amount: 99.99,45});
Key points: