Home > Mobile >  Extend parameters of already defined method
Extend parameters of already defined method

Time:01-16

I am writing a Koa web server, and want to know if its possible to add another parameter to an already defined method on the Koa.app object.

  const mongoState = await connectToDatabase();

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

So in this case mongoState is a local variable that I assign in the app.use(() => {}) closure to the ctx.state.mongoState object.

But I want to write that middleware logic somewhere else and call it inside app.use() like: app.use(dbInjector) or something. The issue is I need to pass that mongoState local variable to the closure inside app.use(). But I can't define a function that takes any more parameters then (ctx, next) for app.use()

I was thinking like this:

app.use(dbInjector(mongoState));

`in a different file`
export const dbInjector = async (ctx, next, mongoState) => ...etc... {}

But this obviously doesn't work. Koa's app.use() will just inject ctx and next automatically, but I am trying to add another param.

Also I don't know the correct terminology for this situation, the app.use() method will just automatically pass the two ctx, next params to the function inside .use(), I am not sure how that works, or what thats called?

CodePudding user response:

You don't need to add an extra parameter. app.use wants a function as first parameter. So, you can create a function that returns the desired function to use in app.use.

const dbInjector = (mongoState) => {
  return async (ctx, next) => {
    ctx.state.mongoState = mongoState;
    await next();
  };
};

And now you can use this in app.use:

app.use(dbInjector(mongoState));
  •  Tags:  
  • Related