UNPKG

better-payment

Version:

Unified payment gateway library for Turkish payment providers

118 lines (117 loc) 3.5 kB
// src/adapters/node.ts function toExpressHandler(handler) { return async (req, res) => { try { const protocol = req.protocol || "http"; const host = req.get("host") || "localhost"; const url = `${protocol}://${host}${req.originalUrl || req.url}`; const betterPayRequest = { method: req.method, url, headers: req.headers, body: await parseExpressBody(req) }; const response = await handler.handle(betterPayRequest); Object.entries(response.headers).forEach(([key, value]) => { res.setHeader(key, value); }); res.status(response.status).json(response.body); } catch (error) { res.status(500).json({ error: true, message: error.message || "Internal server error" }); } }; } function toNodeHttpHandler(handler) { return async (req, res) => { try { const protocol = req.protocol || "http"; const host = req.headers.host || "localhost"; const url = `${protocol}://${host}${req.url}`; const betterPayRequest = { method: req.method || "GET", url, headers: req.headers, body: await parseNodeHttpBody(req) }; const response = await handler.handle(betterPayRequest); res.writeHead(response.status, { ...response.headers, "Content-Type": "application/json" }); res.end(JSON.stringify(response.body)); } catch (error) { res.writeHead(500, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: true, message: error.message || "Internal server error" }) ); } }; } async function parseExpressBody(req) { if (req.method === "GET") { return Object.keys(req.query).length > 0 ? req.query : void 0; } if (req.body && Object.keys(req.body).length > 0) { return req.body; } return new Promise((resolve) => { let body = ""; req.on("data", (chunk) => { body += chunk.toString(); }); req.on("end", () => { try { resolve(body ? JSON.parse(body) : void 0); } catch { resolve(body || void 0); } }); }); } async function parseNodeHttpBody(req) { if (req.method === "GET") { const url = new URL(req.url || "", `http://${req.headers.host}`); const params = {}; url.searchParams.forEach((value, key) => { params[key] = value; }); return Object.keys(params).length > 0 ? params : void 0; } return new Promise((resolve) => { let body = ""; req.on("data", (chunk) => { body += chunk.toString(); }); req.on("end", () => { try { const contentType = req.headers["content-type"] || ""; if (contentType.includes("application/json")) { resolve(body ? JSON.parse(body) : void 0); } else if (contentType.includes("application/x-www-form-urlencoded")) { const params = {}; body.split("&").forEach((pair) => { const [key, value] = pair.split("="); if (key) { params[decodeURIComponent(key)] = decodeURIComponent(value || ""); } }); resolve(params); } else { resolve(body || void 0); } } catch { resolve(body || void 0); } }); }); } var toNodeHandler = toExpressHandler; export { toExpressHandler, toNodeHandler, toNodeHttpHandler }; //# sourceMappingURL=node.mjs.map //# sourceMappingURL=node.mjs.map