UNPKG

beckn-lightweight

Version:

Lightweight Node.js utilities to integrate Beckn protocol into existing BPPs

60 lines (51 loc) 2.45 kB
const axios = require("axios"); const { sendAck } = require("../utils/ackResponse"); const { postCallback } = require("../utils/postCallback"); function createForwardingHandler({ messageKey, callbackAction }) { return function (customLogicFn = null) { return async (req, res) => { const context = req.body.context; const payload = req.body.message?.[messageKey]; console.log("Received /search request. Sending ACK..."); // 2. Send ACK sendAck(res); try { let bppResponse = null; if (customLogicFn) { bppResponse = await customLogicFn(payload, context); } // Use bppResponse if available if (!bppResponse) { // 4. Forward request to actual BPP const bppUri = context.bpp_uri; if (!bppUri) throw new Error("Missing bpp_uri in context"); const forwardUrl = `${bppUri}/${context.action}`; const response = await axios.post(forwardUrl, req.body, { headers: { "Content-Type": "application/json" }, }); bppResponse = response.data; } // 5. Post response to BAP /on_* endpoint await postCallback(callbackAction, context, bppResponse); } catch (err) { console.error(`${callbackAction} forwarding error:`, err.message); } }; }; } // Export handlers module.exports = { handleSearch: createForwardingHandler({ messageKey: "intent", callbackAction: "on_search" }), handleSelect: createForwardingHandler({ messageKey: "order", callbackAction: "on_select" }), handleInit: createForwardingHandler({ messageKey: "order", callbackAction: "on_init" }), handleConfirm: createForwardingHandler({ messageKey: "order", callbackAction: "on_confirm" }), handleStatus: createForwardingHandler({ messageKey: "order_id", callbackAction: "on_status" }), handleTrack: createForwardingHandler({ messageKey: "order_id", callbackAction: "on_track" }), handleCancel: createForwardingHandler({ messageKey: "order", callbackAction: "on_cancel" }), handleSupport: createForwardingHandler({ messageKey: "ref_id", callbackAction: "on_support" }), handleRating: createForwardingHandler({ messageKey: "id", callbackAction: "on_rating" }), handleFeedback: createForwardingHandler({ messageKey: "feedback_form", callbackAction: "on_feedback" }), handleUpdate: createForwardingHandler({ messageKey: "order", callbackAction: "on_update" }), handleIssue: createForwardingHandler({ messageKey: "issue", callbackAction: "on_issue" }), handleIssueStatus: createForwardingHandler({ messageKey: "issue_id", callbackAction: "on_issue_status" }), };