1

I'm using Koa.js and I was wondering how I could use a middleware with router.verb() As mentioned here router.use([path], middleware) I tried like below. The console.log() trigger but the users.list is not called

My main objective is to do an auth middleware

const Router = require("@koa/router");
const router = new Router();
const users = require("./Controllers/users/index.js");

router.use("/user", (ctx, next) => {
    console.log(ctx);
    next();
});

router.get("/user", users.list)

I don't get any error messages but the users.list don't execute.

Then i tried this

router.get("/user", (ctx, next) => {
    console.log(ctx);
    next();
}, users.list)

But i don't get any change and I feel like I don't understand something, but can't figure out what

In my index.js

const Koa = require("koa");
const router = require("./Routes");
const bodyParser = require("koa-bodyparser");
const cors = require("@koa/cors");
const serve = require("koa-static");
const path = require("path");

const errorHandler = require("./Middlewares/errorHandler");
const app = new Koa();

app.use(errorHandler)
    .use(bodyParser())
    .use(cors())
    .use(router.routes())
    .use(serve(path.join("public", "ads")))
    .use(router.allowedMethods());

in my controller

const { Users } = require("../../Models");

module.exports = {
    list: async (ctx, next) => {
        let AllUsers = await Users.findAll();
        ctx.body = AllUsers;
    }
}
L.Castel
  • 36
  • 6

1 Answers1

0

I got it working with adding await next()

router.use("/ads", async (ctx, next) => {
    console.log(ctx);
    await next();
});

Since my controller is an async function I get my explanations from here -> async/await always returns promise

L.Castel
  • 36
  • 6