Just put the method and path in a string mapped to a function in the routes constant and you can have any function run when that path is fetched.
The provided file has some example functions imported from another file.
function test_endpoint (request, env, ctx) { | |
return new Response("test", { status: 200 }); | |
} | |
function example_endpoint (request, env, ctx) { | |
const json = await request.json(); | |
return new Response(json, { status: 200 ,headers: { "content-type": "application/json" },}); | |
} |
import { example_endpoint, test_endpoint } from 'example.js' | |
const routes = { | |
"GET /": () => new Response("This is the router example", { status: 200 }), | |
"GET /test_endpoint": test_endpoint, | |
"POST /example_endpoint": example_endpoint, | |
} | |
export default { | |
async fetch(request, env, ctx) { | |
console.log("Request", request); | |
const { pathname } = new URL(request.url); | |
var route = routes[`${request.method} ${pathname}`]; | |
console.log("Route", `${request.method} ${pathname}`); | |
if (route) { | |
return route(request, env, ctx); | |
} | |
return new Response("Not found", { status: 404 }); | |
}, | |
}; |