UNPKG

@idealite/web-services

Version:

Comprehensive web services library with webhook system and Mux integration

100 lines (99 loc) 2.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseWebhookReceiver = void 0; /** * Abstract base class for webhook receivers * Provides common functionality for receiving and processing webhooks */ class BaseWebhookReceiver { handlers = new Map(); verifier; constructor(verifier) { this.verifier = verifier; } /** * Register an event handler for a specific webhook type */ registerHandler(handler) { const handlers = this.handlers.get(handler.type) || []; handlers.push(handler); this.handlers.set(handler.type, handlers); } /** * Unregister an event handler */ unregisterHandler(type, handler) { const handlers = this.handlers.get(type) || []; const index = handlers.indexOf(handler); if (index > -1) { handlers.splice(index, 1); if (handlers.length === 0) { this.handlers.delete(type); } else { this.handlers.set(type, handlers); } } } /** * Process an incoming webhook payload */ async processWebhook(payload) { const handlers = this.handlers.get(payload.type) || []; if (handlers.length === 0) { await this.handleUnknownType(payload); return; } // Process all handlers for this type await Promise.all(handlers.map(handler => this.safeHandleEvent(handler, payload))); } /** * Verify webhook signature if verifier is configured */ verifyWebhook(payload, signature, secret) { if (!this.verifier) { return true; // No verification configured } return this.verifier.verify(payload, signature, secret); } /** * Safely handle event with error catching */ async safeHandleEvent(handler, payload) { try { await handler.handle(payload); } catch (error) { await this.handleError(error, handler, payload); } } /** * Handle errors that occur during event processing */ handleError(error, handler, payload) { console.error('Webhook handler error:', { error, handlerType: handler.type, payloadId: payload.id, }); } /** * Get all registered handler types */ getRegisteredTypes() { return Array.from(this.handlers.keys()); } /** * Get handlers for a specific type */ getHandlers(type) { return this.handlers.get(type) || []; } /** * Clear all handlers */ clearHandlers() { this.handlers.clear(); } } exports.BaseWebhookReceiver = BaseWebhookReceiver;