open-api icon indicating copy to clipboard operation
open-api copied to clipboard

[express-openapi] Additional Middlewares on routes

Open SkyaTura opened this issue 6 years ago • 11 comments

There is a way of adding additional middlewares on specific routes only?

I was able to add "global" middlewares by adding them to the root of my apiDoc, but it doesn't work if I add it to the method or the path I want.

SkyaTura avatar Jan 26 '20 07:01 SkyaTura

Yes, there is an example of this in the documentation:

  • https://github.com/kogosoftwarellc/open-api/tree/master/packages/express-openapi#typescript-example

This doesn't just work for Typescript of course. The whole idea is to provide an operation wrapped in a array along with its middleware(s):

export default function() {
    async function GET(req, res) {
        // ...
    }

    GET.apiDoc = {
        // ...
    };

    return {
        GET: [someMiddleware(), GET]
    };
};

saalaa avatar Jan 29 '20 20:01 saalaa

But I use operationIds instead of the default auto-load, and passing arrays as and operation doesn't work

SkyaTura avatar Jan 31 '20 18:01 SkyaTura

@SkyaTura not sure what you mean by this:

I use operationIds instead of the default auto-load

jsdevel avatar Feb 07 '20 18:02 jsdevel

https://github.com/kogosoftwarellc/open-api/tree/master/packages/express-openapi#argsoperations @jsdevel

SkyaTura avatar Feb 07 '20 21:02 SkyaTura

So, this shouldn't work any differently. A thorough reading of the Express documentation would make that clear for you.

app.all(path, callback [, callback ...]) [...] Callback functions; can be:

  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

This code should do what you want:

initialize({
  app,
  apiDoc: './apiDoc.yml',
  operations: {
    getFoo: [
      someMiddleware(),
      function(req, res) {
        res.send('foo');
      }
    ]
  }
});

saalaa avatar Feb 07 '20 22:02 saalaa

I will investigate further, but wanted to throw out there that this did not work for me. First, the type definition does not allow arrays for values of operations:

operations?: {
    [operationId: string]: (...arg: any[]) => any;
};

If I ignore it I get TypeError: innerFunction.bind is not a function:

initialize({
  app,
  apiDoc: path.join(__dirname, "/../../spec.v1.json"),
  operations: {
    // @ts-ignore
    postAuthLogin: [
      function(_req: any, res: any) {
        res.send("foo");
      }
    ]
  }
});

ealtunyay avatar Mar 25 '20 23:03 ealtunyay

This is not good.

https://github.com/kogosoftwarellc/open-api/blob/master/packages/openapi-framework/index.ts#L250

From what I read, you could probably get away with creating a function that runs the middlewares/handler stack. Conceptually, this would look like this:

initialize({
  app,
  apiDoc: './apiDoc.yml',
  operations: {
    getFoo: invokeMiddlewares(
      someMiddleware(),
      function(req, res) {
        res.send('foo');
      }
    )
  }
});

It's definitely fiddly but not overly complicated to write, there are many examples available. Have a look at the following:

https://www.bennadel.com/blog/3260-manually-invoking-express-js-middleware-functions.htm

saalaa avatar Mar 25 '20 23:03 saalaa

Thanks for the quick reply and the suggestion. I will look into it.

ealtunyay avatar Mar 26 '20 00:03 ealtunyay

I had a couple issues with the article:

  1. The code is presented as a learning exercise and not meant to be something to put into production
  2. I am unfamiliar with q and because I am not looking for a promise library I was opposed to digging into it just so I can understand the author's code

I looked for other examples like you mentioned, but didn't come up with anything.

Finally, I went looking for a library that would do something similar. I found trough, ware, p-pipe, and a few others that might have done the job. I chose to use trough because it seemed to be the most popular and actively maintained.

Here's some example code:

initialize({
  app,
  apiDoc: path.join(__dirname, "/../../spec.v1.json"),
  operations: {
    postAuthLogin: (() => {
      return (req: any, res: any, next: any) =>
        trough()
          .use((req: any, res: any, next: any) => {
            console.log("middleware");
            next();
          })
          // eslint-disable-next-line no-unused-vars
          .use((req: any, res: any, _next: any) => {
            console.log("route");
            res.end();
          })
          .run(req, res, next);
    })()
  }
});

Working as expected (so far)

ealtunyay avatar Mar 26 '20 15:03 ealtunyay

can this be closed?

jsdevel avatar May 19 '20 22:05 jsdevel

Pretty sure it's ok, yes.

saalaa avatar Jun 10 '20 14:06 saalaa