1

I've got a few middlewares in my app:

  • loggedInUserHandler: Loads the current user and saves it the context
  • notificationHandler: Gets the current user from the context. Then loads the notifications for this user and saves them to the context.
  • routeHandler: Gets the current user and notifications from the context, and loads it into the correct view.

Basically each middleware might depend on the data that previous middlewares produce and attach to the context. For now, I'm simply loading the middlewares in the correct order, like so:

app.use(loggedInUserHandler);
app.use(notificationHandler);
app.use(routeHandler);

However I wonder if there's a better way to do this and perhaps declare the dependencies of each middleware? Then if they are called in the wrong order, an error would be thrown or something similar. I couldn't find much info about this in Koa so I'm wondering if there's a proper way to do it. Any suggestion?

laurent
  • 88,262
  • 77
  • 290
  • 428
  • My initial thoughts are to create an array of these functions, then pass that array in app.use like so: `app.use(async ctx => loadUserNotifications.map(fn => fn.call(ctx)))` but then these functions wouldn't be strictly koa middleware as such – Alejandro Jan 15 '21 at 22:46

1 Answers1

0

If you want to call the next middleware you can use the next() function.
In koa, you need to call the next function asynchronously and wait for it to complete.

eg.

// 1st middleware
app.use(async(a, next) => {
  .
  .
  .

  // Call next middleware and wait for it to complete
  await next()
})

// 2nd middleware
app.use(async(a) => {
  .
  .
})
Ankush Chavan
  • 1,043
  • 1
  • 6
  • 20