UNPKG

valory-adaptor-polka

Version:
82 lines 2.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const valory_runtime_1 = require("valory-runtime"); const qs = require("querystring"); const url = require("url"); const pathReplacer = /{([\S]*?)}/g; const polka = require("polka"); class PolkaAdaptor { constructor() { this.allowDocSite = true; this.disableSerialization = false; this.locallyRunnable = true; this.server = polka(); } register(path, method, handler) { const route = `${path}:${valory_runtime_1.HttpMethod[method]}`; path = path.replace(pathReplacer, ":$1"); this.server.add(valory_runtime_1.HttpMethod[method], path, (req, res) => { let rawBody; req.on("data", (chunk) => { rawBody = chunk.toString(); }); req.on("end", () => { const parsedUrl = url.parse(req.url, true); const body = attemptParse(req.headers["content-type"], rawBody); const transReq = new valory_runtime_1.ApiRequest({ headers: req.headers, query: parsedUrl.query, path: req.params, route, body, rawBody, formData: body, }); handler(transReq).then((response) => { const resContentType = response.headers["Content-Type"] || "text/plain"; res.writeHead(response.statusCode, response.headers); res.end(serialize(resContentType, response.body)); }); }); }); } getExport(metadata, options) { this.server.listen(options.port || process.env.PORT, options.host || process.env.HOST); return { valory: metadata }; } shutdown() { this.server.close(); } } exports.PolkaAdaptor = PolkaAdaptor; function attemptParse(contentType, obj) { if (contentType == null) { return obj; } const parsedContentType = contentType.split(";")[0]; try { switch (parsedContentType) { case "application/json": return JSON.parse(obj); case "application/x-www-form-urlencoded": return qs.parse(obj); default: return obj; } } catch (err) { return obj; } } function serialize(contentType, data) { if (data == null) { return ""; } else if (typeof data !== "string") { return JSON.stringify(data); } else { return data; } } //# sourceMappingURL=adaptor-polka.js.map