Echo JS 0.11.0

<~>

tracker1 1513 days ago. link 0 point
Not really code or JS centric and doesn't really dive into the issue at all with useful examples.  It's a low quality post.

Personally, I'd say it depends... you should absolutely load middleware separate from your controllers.  In terms of service separation, it depends.  If it's a really simple DB call without much abstraction, I'd say do it in your controllers.

With koa, I add a database connection object to the context (context.db or context.sql) that makes it ready to go... this way I can use:

    router.get('/foo/:id',
      router.validate({
        params: Joi.object({
          id: ...
        })
      }),
      router.authorize('admin'),
      async ctx => {
        ctx.body = await ctx.sql`
          SELECT ...
          FROM ...
          WHERE Foo.id = ${ctx.params.id}
        `;
      },
    );

I use koa router for all of my api routes, and mount it to `/api` at a higher level.  I also add a validate and authorize function to the router.  This way, I can add Joi validation schemas to body and/or params, etc.  The authorize method inputs `(...roles)` so I can just add any required roles, if no role is specified, it still must have a logged in api token (jwt) with the request, but any role allowed.

In this case, separating out the sql query into a separate service or data access layer doesn't add value imho.