losikov / api-example

MIT License
130 stars 47 forks source link

Question: swagger-routes-express and express-openapi-validator #1

Open hlim7 opened 3 years ago

hlim7 commented 3 years ago

Hi , first of all thanks for open sourcing this. This is exactly what I'm looking for. I was wondering why do you need both swagger-routes-express and express-openapi-vaidator. It seems like they do the same thing which automatically creates the routes using the the open api schema? Or am I missing something.

Thanks in advance!

losikov commented 3 years ago

Hi @hlim7,

swagger-routes-express builds routes automatically to the functions exported in src/api/controllers/index.ts using operationId parameter as a function name for each path in config/openapi.yml.

express-openapi-vaidator, validates all query parameters, request and response body based on the schema in config/openapi.yml. If it doesn't match the schema, it will respond to a client's request with a default response, or with the one you specify in src/utils/server.ts:

// error customization, if request is invalid
server.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  res.status(err.status).json({
    error: {
      type: 'request_validation',
      message: err.message,
      errors: err.errors
    }
  })
})
hlim7 commented 3 years ago

Hi @losikov I believe express-openapi-validator also has the option to connect the routes automatically using x-eov-operation-id and x-eov-operation-handler in the openapi.yaml so if you specify it like this

paths:
  /hello:
    get:
      description: Returns 'Hello <name>/stranger!!!' to the caller
      tags: 
        - greeting
      operationId: hello
      x-eov-operation-id: hello
      x-eov-operation-handler: controller/user

Here's the doc ref from express-openapi-validator re: how to use operationHandlers https://www.npmjs.com/package/express-openapi-validator#example-express-api-server-with-operationhandlers

losikov commented 3 years ago

@hlim7, thanks for showing it! I will try it.