DEV Community

Discussion on: Create a Simple REST API with DENO and OAK framework

Collapse
 
coyotte508 profile image
coyotte508 • Edited

A few things I learned from Koa (from which Oak is inspired):

  • You don't need to set the status of the response to 200, if you set its body to something
  • You don't need to send a 404, just return without touching response.body

You can set a middleware to handle error http codes, if you want to send a JSON payload along with the status, without specifying the error payload in each of your routes:

app.use(async (ctx, next) => {
  await next();

  if (ctx.response.status >= 400) {
    let message = "Error";
    switch (ctx.response.status) {
      case 404: message = "Not Found"; break;
    }
    ctx.response.body = {success: false, message};
  }
});
Enter fullscreen mode Exit fullscreen mode

All that should simplify the code of your router handlers a fair bit :)