I am working on deno
equivalent of my node (express)
server application for study purposes and I can't find a way to apply optional
chunks when defining routes
.
For example in express
application i have route: /search/:start/:records?
import { Application } from "https://deno.land/x/[email protected]/mod.ts";
import { search } from "./controllers/data.ts";
const app = new Application();
const PORT = 80;
app.get("/search/:start/:records?", search);
app.start({ port: PORT });
For my experimentation with deno
i picked lib
abc that seemed similar to express
.
When runtime is launched my old routes are working, except the optional chunk, they are not optional anymore, instead they need to be provided or error 404
is being returned.
Does someone have experience with handling optional parameters and deno
?
CodePudding user response:
I don't know a whole lot about abc
, but oak
is currently the most commonly-used http server framework for Deno (and I think it would be the analog of Express based on the metric of popularity).
It uses path-to-regexp
for parsing path strings (which is also what Express uses), so it allows for optional parameters using the same syntax with which you're already familiar.
Here's an example of creating a route like the one in your question using Oak, and sending the path parameter values as properties in a JSON response:
import { Application, Router } from "https://deno.land/x/[email protected]/mod.ts";
const router = new Router();
router.get("/search/:start/:records?", async (ctx, next) => {
const { start, records = null } = ctx.params;
const json = JSON.stringify({ start, records }, null, 2);
ctx.response.body = json;
ctx.response.type = "application/json";
await next();
});
const app = new Application();
app
.use(router.routes())
.use(router.allowedMethods());
await app.listen({ port: 8000 });
CodePudding user response:
abc
does not support optional chunks yet.