UNPKG

dt-common-device

Version:

A secure and robust device management library for IoT applications

255 lines (254 loc) 9.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ExamplePmsController = exports.ExamplePmsServiceWithQueue = void 0; exports.exampleUsage = exampleUsage; const WebhookQueueIntegration_1 = require("../services/WebhookQueueIntegration"); /** * Example: How to integrate webhook queue with existing PMS service * * This example shows how to modify your existing PMS service to use * the webhook queue system without major refactoring. */ // Configuration for the webhook queue const webhookQueueConfig = { redisHost: process.env.REDIS_HOST || "localhost", redisPort: parseInt(process.env.REDIS_PORT || "6379"), maxRetries: 3, backoffDelay: 2000, jobTimeout: 300000, // 5 minutes removeOnComplete: { age: 3600000, count: 100 }, // 1 hour, max 100 removeOnFail: { age: 7200000, count: 50 }, // 2 hours, max 50 }; // Example: Modified PMS Service with webhook queue integration class ExamplePmsServiceWithQueue { constructor() { this.webhookQueueIntegration = new WebhookQueueIntegration_1.WebhookQueueIntegration(); } /** * Initialize the webhook queue system */ async initializeWebhookQueue() { try { // Initialize with your existing webhook processing logic await this.webhookQueueIntegration.initialize(webhookQueueConfig, this.processWebhook.bind(this) // Bind to existing method ); console.log("Webhook queue initialized in PMS service"); } catch (error) { console.error("Failed to initialize webhook queue:", error); throw error; } } /** * Your existing webhook processing method * This will be called by the queue worker */ async processWebhook(webhookData, pmsType) { console.log(`[PMS Service] Processing webhook for PMS: ${pmsType}`); try { // Your existing webhook processing logic here // This could include: // - Calling handleWebhookEvents // - Database operations // - Business logic // - etc. // Simulate processing await this.simulateWebhookProcessing(webhookData, pmsType); console.log(`[PMS Service] Webhook processed successfully for PMS: ${pmsType}`); return { success: true, processedAt: new Date().toISOString() }; } catch (error) { console.error(`[PMS Service] Error processing webhook for PMS: ${pmsType}:`, error); throw error; } } /** * Modified webhook handler that queues webhooks instead of processing directly */ async handleWebhookWithQueue(webhookData, pmsType, propertyId) { try { // Extract propertyId from webhook if not provided const extractedPropertyId = propertyId || this.extractPropertyIdFromWebhook(webhookData); if (!extractedPropertyId) { // Fallback to direct processing if propertyId cannot be extracted console.warn("Could not extract propertyId, processing webhook directly"); return await this.processWebhook(webhookData, pmsType); } // Queue the webhook for processing const jobId = await this.webhookQueueIntegration.queueWebhook(extractedPropertyId, pmsType, webhookData); console.log(`Webhook queued successfully with job ID: ${jobId}`); return jobId; } catch (error) { console.error("Failed to queue webhook:", error); // Fallback to direct processing console.log("Falling back to direct webhook processing"); return await this.processWebhook(webhookData, pmsType); } } /** * Get webhook queue status for monitoring */ async getWebhookQueueStatus(propertyId, pmsType) { if (!this.webhookQueueIntegration.isReady()) { throw new Error("Webhook queue not initialized"); } return await this.webhookQueueIntegration.getQueueStatus(propertyId, pmsType); } /** * Get all webhook queue statuses for a property */ async getAllWebhookQueueStatuses(propertyId) { if (!this.webhookQueueIntegration.isReady()) { throw new Error("Webhook queue not initialized"); } return await this.webhookQueueIntegration.getAllQueueStatuses(propertyId); } /** * Clean up old webhook jobs */ async cleanupWebhookQueues(propertyId) { if (!this.webhookQueueIntegration.isReady()) { return; } const pmsTypes = ["CLOUDBEDS", "HOTELKEY", "STAYNTOUCH"]; for (const pmsType of pmsTypes) { try { await this.webhookQueueIntegration.cleanupQueue(propertyId, pmsType); console.log(`Cleaned up webhook queue for ${propertyId}_${pmsType}`); } catch (error) { console.error(`Failed to cleanup queue for ${propertyId}_${pmsType}:`, error); } } } /** * Shutdown webhook queue system */ async shutdownWebhookQueue() { if (this.webhookQueueIntegration.isReady()) { await this.webhookQueueIntegration.shutdown(); } } // Helper methods extractPropertyIdFromWebhook(webhookData) { // Implement your logic to extract propertyId from webhook data // This will depend on how each PMS sends the propertyId return webhookData.propertyId || webhookData.property_id || null; } async simulateWebhookProcessing(webhookData, pmsType) { // Simulate some processing time await new Promise((resolve) => setTimeout(resolve, 100)); // Simulate different processing logic based on PMS type switch (pmsType) { case "CLOUDBEDS": console.log("Processing Cloudbeds webhook..."); break; case "HOTELKEY": console.log("Processing HotelKey webhook..."); break; case "STAYNTOUCH": console.log("Processing StayNTouch webhook..."); break; default: console.log("Processing unknown PMS webhook..."); } } } exports.ExamplePmsServiceWithQueue = ExamplePmsServiceWithQueue; // Example: How to use in your existing controller class ExamplePmsController { constructor() { this.pmsService = new ExamplePmsServiceWithQueue(); } /** * Initialize the service (call this when your app starts) */ async initialize() { await this.pmsService.initializeWebhookQueue(); } /** * Modified webhook endpoint that uses the queue */ async handleWebhook(payload, pmsType) { try { // Try to extract propertyId from the webhook payload const propertyId = this.extractPropertyIdFromPayload(payload); if (propertyId) { // Use the queue system const jobId = await this.pmsService.handleWebhookWithQueue(payload, pmsType, propertyId); return { message: "Webhook queued successfully", jobId, propertyId, pmsType, }; } else { // Fallback to direct processing console.warn("PropertyId not found, processing webhook directly"); return await this.pmsService.processWebhook(payload, pmsType); } } catch (error) { console.error("Error handling webhook:", error); throw error; } } /** * Get webhook queue status */ async getWebhookQueueStatus(propertyId, pmsType) { return await this.pmsService.getWebhookQueueStatus(propertyId, pmsType); } /** * Get all webhook queue statuses for a property */ async getAllWebhookQueueStatuses(propertyId) { return await this.pmsService.getAllWebhookQueueStatuses(propertyId); } /** * Cleanup webhook queues */ async cleanupWebhookQueues(propertyId) { await this.pmsService.cleanupWebhookQueues(propertyId); } /** * Shutdown the service */ async shutdown() { await this.pmsService.shutdownWebhookQueue(); } extractPropertyIdFromPayload(payload) { // Implement your logic to extract propertyId return payload.propertyId || payload.property_id || null; } } exports.ExamplePmsController = ExamplePmsController; // Example: Usage in your application async function exampleUsage() { try { // 1. Create controller const controller = new ExamplePmsController(); // 2. Initialize await controller.initialize(); // 3. Handle webhooks (they will be queued) const webhookPayload = { eventType: "reservation.created", propertyId: "hotel123", reservationId: "res_001", }; const result = await controller.handleWebhook(webhookPayload, "CLOUDBEDS"); console.log("Webhook result:", result); // 4. Check queue status const status = await controller.getWebhookQueueStatus("hotel123", "CLOUDBEDS"); console.log("Queue status:", status); // 5. Cleanup when done await controller.cleanupWebhookQueues("hotel123"); // 6. Shutdown await controller.shutdown(); } catch (error) { console.error("Example usage failed:", error); } }