Simple Router Function
Here's an example of a simple router function: one function handling multiple paths using only standard lib parsing.
xxxxxxxxxx
32
module.exports = { handler };
function json(statusCode, obj) {
return {
statusCode,
headers: { "content-type": "application/json" },
body: JSON.stringify(obj)
};
}
async function handler(event) {
const path = event.path || "/";
const method = (event.httpMethod || "GET").toUpperCase();
if (method === "GET" && path === "/health") {
return json(200, { ok: true });
}
if (method === "POST" && path === "/echo") {
const body = typeof event.body === "string" ? event.body : JSON.stringify(event.body || {});
return json(200, { youSent: body });
}
return json(404, { error: "not found", path, method });
}
if (require.main === module) {
(async () => {
console.log(await handler({ path: "/health", httpMethod: "GET" }));
console.log(await handler({ path: "/echo", httpMethod: "POST", body: { a: 1 } }));
})();
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment