import * as Hapi from "@hapi/hapi"; import Toys from "@hapipal/toys"; import WhatsappService from "./service"; const withDefaults = Toys.withRouteDefaults({ options: { cors: true, }, }); const getService = (request: Hapi.Request): WhatsappService => { const { whatsappService } = request.services(); return whatsappService as WhatsappService; }; interface MessageRequest { phoneNumber: string; message: string; attachments?: Array<{ data: string; filename: string; mime_type: string }>; } export const SendMessageRoute = withDefaults({ method: "post", path: "/api/bots/{id}/send", options: { description: "Send a message", async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) { const { id } = request.params; const { phoneNumber, message, attachments } = request.payload as MessageRequest; const whatsappService = getService(request); await whatsappService.send( id, phoneNumber, message as string, attachments, ); request.logger.info( { id, attachmentCount: attachments?.length || 0, }, "Sent a message at %s", new Date().toISOString(), ); return _h .response({ result: { recipient: phoneNumber, timestamp: new Date().toISOString(), source: id, }, }) .code(200); }, }, }); export const ReceiveMessageRoute = withDefaults({ method: "get", path: "/api/bots/{id}/receive", options: { description: "Receive messages", async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) { const { id } = request.params; const whatsappService = getService(request); const date = new Date(); const twoDaysAgo = new Date(date.getTime()); twoDaysAgo.setDate(date.getDate() - 2); request.logger.info({ id }, "Received messages at %s", new Date().toISOString()); return whatsappService.receive(id, twoDaysAgo); }, }, }); export const RegisterBotRoute = withDefaults({ method: "post", path: "/api/bots/{id}/register", options: { description: "Register a bot", async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) { const { id } = request.params; const whatsappService = getService(request); await whatsappService.register(id); /* , (error: string) => { if (error) { return _h.response(error).code(500); } request.logger.info({ id }, "Register bot at %s", new Date()); return _h.response().code(200); }); */ return _h.response().code(200); }, }, }); export const UnverifyBotRoute = withDefaults({ method: "post", path: "/api/bots/{id}/unverify", options: { description: "Unverify bot", async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) { const { id } = request.params; const whatsappService = getService(request); return whatsappService.unverify(id); }, }, }); export const GetBotRoute = withDefaults({ method: "get", path: "/api/bots/{id}", options: { description: "Get bot info", async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) { const { id } = request.params; const whatsappService = getService(request); return whatsappService.getBot(id); }, }, });