rescript-rest
Version:
😴 ReScript RPC-like client, contract, and server implementation for a pure REST API
81 lines (77 loc) • 2.94 kB
JavaScript
// Generated by ReScript, PLEASE EDIT WITH CARE
;
var Rest = require("./Rest.res.js");
var Js_exn = require("rescript/lib/js/js_exn.js");
var S$RescriptSchema = require("rescript-schema/src/S.res.js");
var Caml_js_exceptions = require("rescript/lib/js/caml_js_exceptions.js");
function handler(route, implementation) {
var match = Rest.params(route);
var isRawBody = match.isRawBody;
var outputSchema = match.outputSchema;
var inputSchema = match.inputSchema;
var path = match.path;
var method = match.method;
match.pathItems.forEach(function (pathItem) {
if (typeof pathItem === "string") {
return ;
}
throw new Error("[rescript-rest] " + ("Route " + path + " contains a path param " + pathItem.name + " which is not supported by Next.js handler yet"));
});
return async function (req, res) {
if (req.method !== method) {
return res.status(404).end();
}
if (req.body === undefined) {
var rawBody = {
contents: ""
};
await new Promise((function (resolve, reject) {
req.on("data", (function (chunk) {
rawBody.contents = rawBody.contents + chunk;
}));
req.on("end", resolve);
req.on("error", reject);
}));
req.body = isRawBody ? rawBody.contents : JSON.parse(rawBody.contents);
} else if (isRawBody) {
Js_exn.raiseError("Routes with Raw Body require to disable body parser for your handler. Add `let config: RestNextJs.config = {api: {bodyParser: false}}` to the file with your handler to make it work.");
}
var input;
try {
input = S$RescriptSchema.parseOrThrow(req, inputSchema);
}
catch (raw_error){
var error = Caml_js_exceptions.internalToOCamlException(raw_error);
if (error.RE_EXN_ID === S$RescriptSchema.Raised) {
return res.status(400).json({
error: S$RescriptSchema.$$Error.message(error._1)
});
}
throw error;
}
try {
var implementationResult = await implementation({
input: input,
req: req,
res: res
});
var data = S$RescriptSchema.reverseConvertOrThrow(implementationResult, outputSchema);
var headers = data.headers;
if (headers !== undefined) {
Object.keys(headers).forEach(function (key) {
res.setHeader(key, headers[key]);
});
}
return res.status((data.status || 200)).json(data.data);
}
catch (raw_error$1){
var error$1 = Caml_js_exceptions.internalToOCamlException(raw_error$1);
if (error$1.RE_EXN_ID === S$RescriptSchema.Raised) {
return Js_exn.raiseError("Unexpected error in the " + path + " route: " + S$RescriptSchema.$$Error.message(error$1._1));
}
throw error$1;
}
};
}
exports.handler = handler;
/* Rest Not a pure module */