UNPKG

valory-adaptor-fastify

Version:
77 lines 2.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const valory_runtime_1 = require("valory-runtime"); const fastify = require("fastify"); const querystring_1 = require("querystring"); const pathReplacer = /{([\S]*?)}/g; class FastifyAdaptor { constructor() { this.locallyRunnable = true; this.allowDocSite = true; this.instance = fastify({}); this.instance.addContentTypeParser("application/x-www-form-urlencoded", { parseAs: "string" }, formParser); this.instance.addContentTypeParser("application/json", { parseAs: "string" }, jsonParser); } register(path, method, handler) { const route = `${path}:${valory_runtime_1.HttpMethod[method]}`; path = path.replace(pathReplacer, ":$1"); this.instance.route({ method: valory_runtime_1.HttpMethod[method], url: path, handler: (req, res) => { // FIXME: setting both formData and body is lazy, need a better solution const transRequest = new valory_runtime_1.ApiRequest({ headers: req.req.headers, body: null, rawBody: null, formData: req.body, query: req.query, path: req.params, route, }); const contentType = req.req.headers["content-type"]; if (contentType != null && contentType.indexOf("application/json") !== -1 && req.body != null) { transRequest.body = req.body.parsed; transRequest.rawBody = req.body.raw; } else { transRequest.body = req.body; } return handler(transRequest).then((response) => { if (response.headers["Content-Type"] === "application/json" && typeof response.body === "string") { res.serializer(noopSerializer); } res.code(response.statusCode); res.headers(response.headers); res.send(response.body); }); }, }); } getExport(metadata, options) { this.instance.listen(options.port || process.env.PORT, options.host || process.env.HOST); return { valory: metadata }; } shutdown() { this.instance.server.close(); } } exports.FastifyAdaptor = FastifyAdaptor; function noopSerializer(data) { return data; } function jsonParser(req, body, done) { let json = null; try { json = JSON.parse(body); } catch (err) { err.statusCode = 400; return done(err, undefined); } done(null, { parsed: json, raw: body }); } function formParser(req, body, done) { done(null, querystring_1.parse(body)); } //# sourceMappingURL=adaptor-fastify.js.map