dinatra
dinatra copied to clipboard
Separate params and http body to avoid confusion
Hi! Again: thanks for this project 😄
I am wondering if it would make more sense to separate the HTTP response body from params
, in Context
. This makes the code more explicit and readable, in my opinion. For example:
app(post("/posts/:id/comments", ({ params, body }) => {
console.log(`comment on post: ${params.id}`);
console.log(`comment data: `, body);
return [201, "Created comment"];
}))
Furthermore, this may cause ambiguity as to what data belongs to URL params and what data belongs to the HTTP body. Consider this (somewhat contrived) example:
interface Comment {
post_id: string,
id: string,
text: string,
};
app(
// Todays solution:
post("/posts/:id/comments", ({ params }) => {
//`params.id` -> ID of post or ID of comment?
const comment = { post_id: params.id, id: params.id, text: params.text}
return [201, "Created comment"];
}),
// Proposed solution:
post("/posts/:id/comments", ({ params, body }) => {
// No ambiguity between `params.id` and `body.id`
const comment = body
return [201, "Created comment"];
})
);
I implemented a solution here. If you're interested, I'll submit a PR 😄 However, I believe this breaks with Sinatra, so it's completely reasonable to dissagree.
What do you think?
EDIT: typo and added link to implementation
Are there any changes nececcary for the PR for this to get merged? I would be happy to implement them! 😄