Code Monkey home page Code Monkey logo

openapi-backend's People

Contributors

anttiviljami avatar conorhaining avatar danielfone avatar dependabot[bot] avatar devoto13 avatar drodil avatar elby22 avatar fetchinator7 avatar floedelmann avatar henhal avatar jej2003 avatar juliancataldo avatar lgtm-com[bot] avatar mattdistefano avatar monsterzz avatar mull avatar paulroho avatar richardgarnier avatar sgentle avatar tanukisharp avatar wszydlak avatar yengas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

openapi-backend's Issues

express-typescript fails with strict mode on

The example only works if the strict mode is set to false in the tsconfig.json file. The main error i ran into is:

index.ts:63:41 - error TS2345: Argument of type 'import("/tmp/openapi-backend/examples/express-typescript/node_modules/@types/express-serve-static-core/index").Request' is not assignable to parameter of type 'import("/tmp/openapi-backend/examples/express-typescript/node_modules/openapi-backend/router").Request'.
  Types of property 'headers' are incompatible.
    Type 'IncomingHttpHeaders' is not assignable to type '{ [key: string]: string | string[]; }'.
      Index signatures are incompatible.
        Type 'string | string[] | undefined' is not assignable to type 'string | string[]'.
          Type 'undefined' is not assignable to type 'string | string[]'.

app.use((req, res) => api.handleRequest(req, req, res));

I tried to find a workaround other than disabling the strict mode, but without any success. Maybe this issue is related to #38

oneOf, anyOf, allOf, not implemented?

Hello,

I'm trying to use the OpenAPI feature to have a request body which is able to receive 2 or more types of body object structures, e.g:

(As mentioned here: https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/#oneof)

Paths:

paths:
  '/pets':
    get:
      summary: List pets
      description: Find a list of pets
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Pet'

    post:
      summary: Spawn animal
      requestBody:
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/Cat'
                - $ref: '#/components/schemas/Dog'
      responses:
        '200':
          description: OK

With corresponding components:

components:
  schemas:

    Pet:
      type: object
      properties:
        id:
          type: integer
          format: int64
          example: 4

    Dog:
      type: object
      properties:
        id:
          type: integer
          format: int64
          example: 4
        bark:
          type: boolean
        breed:
          type: string
          enum: [Dingo, Husky, Retriever, Shepherd]

    Cat:
      type: object
      properties:
        id:
          type: integer
          format: int64
          example: 4
        hunts:
          type: boolean
        age:
          type: integer

I try to send this object:

{"id":423,"bark":true,"breed":"Dingo"}

Because currently I'm getting this error:
HTTP status: 400

{
  "err": [
    {
      "keyword": "oneOf",
      "dataPath": ".requestBody",
      "schemaPath": "#/properties/requestBody/oneOf",
      "params": {
        "passingSchemas": [
          0,
          1
        ]
      },
      "message": "should match exactly one schema in oneOf"
    }
  ]
}

Update Handler typing with generic request and response types

In order to get better typing on the arguments for the Handler type, does it make sense to use generics for the request and response arguments?

For example, what if there was:

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'
import { Params, ParamsDictionary } from 'express-serve-static-core'
import { Request } from 'openapi-backend'
import { Context } from 'openapi-backend/backend'

export type Handler<
  TRequest extends Request = any,
  TResponse = any
> = (context: Context, req: TRequest, res: TResponse, ...args: any[]) => any | Promise<any>;

export type OpenApiExpressRequest<
  P extends Params = ParamsDictionary,
  ResBody = any,
  ReqBody = any
  > = ExpressRequest<P, ResBody, ReqBody> & Request

export type ExpressHandler<
  P extends Params = ParamsDictionary,
  ResBody = any,
  ReqBody = any
> = Handler<OpenApiExpressRequest<P, ResBody, ReqBody>, ExpressResponse<ResBody>>

This way, when writing handlers for an express-backed service, they could be typed as:

import { ExpressHandler } from 'openapi-backend/backend'

export const getById: ExpressHandler = (c, req, res) => {
  res.status(200).json({ message: `getById: ${req.path}` })
}

Thoughts?

Option to pass the parsed request to the handlers

In a lot of cases, since the easiest way to use this is as a catch-all handler to avoid defining routes in many places, some tasks usually left to the framework like routing and parsing path parameters from the URI are not performed. Good-guy openapi-backend could help with this by adding an option to pass the parsed version of the request to handlers.

Perhaps some sort of context object as the first parameter of the handler could make sense. This would allow us to pass the operation object to the handler as well.

QUESTION: What's the best way to handle API versioning? Etherpad

We're looking to start using this module in Etherpad, we're currently using node-express-swagger and that is not well maintained. Would someone from this project be interesting in working with us to do the integration (compensation is available). Ideally someone with express and openapi-backend knowledge :)

In Etherpad we have a Base API (v1) then as we added new/modified calls our API version increased. See https://github.com/ether/etherpad-lite/blob/develop/src/node/handler/APIHandler.js#L47 for code.

I looked to have multiple definition objects but that didn't work. I read through the docs and I must be going blind because I just can't see how I should set this up.. Really sorry, I'm sure this must be user error!

Response validation

Hi,

First of all, amazing library! This is exactly what I was looking for all this time, giving total control, yet offering very useful features for OpenAPI 3. Just needed to say that, this-is-great :)

I was wondering about HTTP response validation though. Do you think there is a reasonable approach to validate HTTP responses against the OpenAPI definition? Perhaps too much overhead in production, but would be very useful during development and while running a test suite.

Would love to hear your thoughts. Thanks!

Incorrect 2.0.0 release on NPM

It looks like the the release 2.0.0 on NPM does not contain the changes from the last merged PRs. Did you forget to npm run build before publishing?

Is there a way to serve multiple mocks under same path ?

Hi,
Maybe it's not possible, but I'm trying to serve multiple mocks under same path but without success.
I have multiple openapi spec files and I need to create a unique mock server
The only way I found is to use different routes like this:

app.use('/' + spec + '/', (req, res) => api.handleRequest(req, req, res));

where spec is the name of every single spec. And the result is:

/spec1/api/pets
/spec2/api/books
/spec3/another/service
...

Is there a way to serve all under same path (eg. / ) ?

Thank you

Support for multiple content types per route

In the OpenAPI spec, it is possible to describe a single route which accepts request bodies of different content types: Specification Swagger docs

Is this supported in openAPI backend?

In my project, I have an endpoint which accepts both application/json and multipart/form-data requests.

Either work if only the respective content type is specified in my openAPI schema, but if both are specified in the doc then only application/json requests succeed.

Support defining query params as object properties

OpenAPI 3.x supports specifying accepted query parameters as a schema object, which among other things allows API spec authors to accept free-form parameters ๐ŸŽ‰

Unfortunately, this does not currently work in OpenAPI Backend - I added a PR here with a failing test suite to demonstrate: #83

Here's an example from the docs:

{
  "in": "query",
  "name": "freeForm",
  "schema": {
    "type": "object",
    "additionalProperties": {
      "type": "integer"
    },
  },
  "style": "form"
}

[Question/Comments] Security Handlers etc.

Hi,
I've been playing with openapi-backend and so far I've found it to be the most complete package to use with OAS. ๐Ÿ‘

I have a few comments/questions

Security Handlers: I kind of like the way the swagger-routes-express package implements it. How is security handled in openapi-backend?

Mapping to nested API routes in swagger-routes-express is also kind of cool.

Even though we can use apiRoot to indicate the matched relative to apiRoot, it is kind of limited right now and it effectively creates two routes, one on the root and one appended to the apiRoot In swagger-routes-express, I like how you can map your api root by tag. i.e. "root" and the rest will default to the defined default servers see here

Overall the two packages seem to have quite a bit in common. I would be nice to join forces :-)

Not valid validation error when using mockResponseForOperation

I have error when I use requestBody in yaml and use mockResponseForOperation:

[ { keyword: 'required',
    dataPath: '',
    schemaPath: '#/required',
    params: { missingProperty: 'requestBody' },
    message: 'should have required property \'requestBody\'' } ]

How to reproduce in openapi-backend project:

  1. install koa
  2. run minimal case
const OpenAPIBackend = require('.').default
const Koa = require('koa')

const app = new Koa()

const api = new OpenAPIBackend({
    definition: '__tests__/resources/example-pet-api.openapi.yml',
    handlers: {
        validationFail: async (c, ctx) => {
            console.log(c.validation.errors)
            ctx.body = { err: c.validation.errors }
            ctx.status = 400
        },
        notFound: async (c, ctx) => {
            ctx.body = { err: 'not found' }
            ctx.status = 404
        },
        notImplemented: async (c, ctx) => {
            const { status, mock } = c.api.mockResponseForOperation(c.operation.operationId)
            ctx.body = mock
            ctx.status = status
        }
    }
})

api.init()

app.use((ctx) => api.handleRequest(
    {
        method: ctx.request.method,
        path: ctx.request.path,
        body: ctx.request.body,
        query: ctx.request.query,
        headers: ctx.request.headers
    },
    ctx
))

app.listen(9000, () => console.info('app listening at http://0.0.0.0:9000'))
  1. do request to url with requestBody in yml
curl -i -X POST "http://0.0.0.0:9000/pets" -H "Content-Type: application/json" -d '{"name":"Garfield"}'

@anttiviljami
I don't understand where is problem.

Separate paths with trailing slash from non-trailing slash paths

I was working with this lib and noticed that it strips all trailing slash in an attempt to normalize paths.

There's just one problem with that - a trailing slash actually has semantic meaning in REST architecture.

This decision looks very intentional given that regex in the router and there are about four or five tests written to prove that the path matching will ignore trailing slashes, so I wanted to bring it up here as a discussion before issuing a pull request.

Why was this decision made to ignore semantically accurate trailing slashes?

Is there a way to inject middleware before hitting the operation logic?

First, I love this tool! Thanks a bunch for putting this together.

Second, I'm looking for something like a "preResponseHandler" of sorts. I'm looking to check a specific header on the request and potentially circumvent the operation if a condition exists. Is there something like that today?

Handling of errors (exceptions) within operation handlers

I am wondering how the handling of exceptions should be done for exceptions that could happen within operations handlers. Can't find anything in the documentation or the examples. Is it:

(A) Every operation handler is supposed to implement its own error handling.

(B) I would like to have exceptions from whitin the operations handler get caught in handleRequest(), stored in the context and then passed to the postResponseHandler (or an dedicated error handler). Here the error could be properly logged and clean a (status 500) response could be sent to the client.

(C) Is the idea to use another mechanism which I did not understand?

Thanks for your thoughts.

Add response mocking from JSON schema

We could easily provide a way to mock non-implemented endpoints with OpenAPI response examples / generated from schema.

The notImplemented-handler could receive a mock response object.

Overriding a required parameter causes schema error

OAS 3 allows overriding parameters at operation level. I noticed that overriding a required parameter gives error as long as I keep it required at both path-level and operation-level.
https://swagger.io/docs/specification/describing-parameters/#common-for-path:

Specific path-level parameters can be overridden on the operation level, but cannot be removed.

- there is an example with override, and here is a gist with that example, producing error - https://gist.github.com/romkhub/71ec632d37d1e1b4057ca652c82d3947 - error is

Error: schema is invalid: data.properties['path'].required should NOT have duplicate items (items ## 1 and 0 are identical)

Allow runtime validation from operation objects

RIght now all our validation functionality relies on pre-built validators instantiated during the api.init() phase.

It would be cool if we could allow validation with non-pre-built operation objects / schemas as well.

Support Swagger 2

We should support providing swagger 2 as an input document and internally upgrading it to OAS 3

Issues with async/await in handlers

When playing with the library, I found two issues when using asynchronous code in my handlers. I'm using it with koa, but I think the problem would be the same for every framework.

First, the calls to the handlers are not awaited, meaning I can't do async work in the handler.
There is a possible fix here.

Second, its a really small one but since we only have one instance of the validation function, the validation errors can be lost in the case a async call is made in the error handler.
For example, is the following handler is registered as validationFail, c.validation.errors in the body can contains a different error.

module.exports = async (c, req) => {
  await logToElasticsearch(c.validation.errors);
  req.response.status = 400;
  req.response.body = c.validation.errors;
};

This is obviously easy to fix like this:

module.exports = async (c, req) => {
  const errors = c.validation.errors;
  await logToElasticsearch(errors);
  req.response.status = 400;
  req.response.body = errors;
};

That being said I made a small patch for this aswell.

Feel free to reuse any of this, and/or close the issue.

Finer-grained response validation

Currently the output validation is performed per operation, as implemented in the buildResponseValidatorForOperation function. It ignores the status, and then create a oneOf schema. I think it could bring more value to take the status code into account.

I would like to suggest an improvement here.

The function validateResponse could take that status code as argument, in order to keep it framework independent and not having to grab it from the res argument. To this end, the function getResponseValidatorForOperation would need to take the status as argument too.

Therefore, probably requiring to change

public responseValidators: { [operationId: string]: Ajv.ValidateFunction };

to

// made multi-line for clarity purpose
public responseValidators: {
    [operationId: string]: {
        [statusCode: string]: Ajv.ValidateFunction
    }
};

Note that I can contribute by making a PR if that can help you.

Thank you for your consideration.

Request object in context contains correct parameters, request object passed as second parameters does not contain parameters

Say if you have an OpenAPI specification:

/my/path/{id}:
 operationID: myPathById
 ... etc

And then have this callback:

export async function myPathById(context: Context, request: Request, response: Response) {
 // context.request.params contains "id" = ...
 // request.params does not contain "id".
}

The "request" object doesn't have the parameters in it, but the context does -- shouldn't these be consistent?

Thanks :)

Issue when upgrading from V2.4.0 to V3.2.0

All was working well with V2.4.0 for the longest time - thanks. I upgraded to V3.2.0 and now my url is not found by the OpenAPIBackend instance, i.e. the correct handler is not found and it goes to the notFound handler. By trying different versions I traced back the issue as being introduced between v3.0.0 and v3.0.1. I noticed you added an extra test in v3.0.1 in router.ts:

// make sure request path matches apiRoot
if (!req.path.startsWith(this.apiRoot)) {
return undefined;
}

I use Express and set my apiRoot ('api-v1') as a mountpath to route api requests which means req.path will not include the apiRoot (as per Express docs: "When called from a middleware, the mount point is not included in req.path. See app.use() for more details.").

Can you review and let me know your thoughts please?

[Question] Can we use both handlers definition in OpenAPIBackend and api.register?

I've been playing with openapi-backend for a little bit and I am still trying to understand how it works.
I should be able to combine handlers definitions in OpenAPIBackend and api.register right? Because I tried and I get:

(node:39783) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/usr/local/2019/openapi-backend-examples/express-resp-validation/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/usr/local/2019/openapi-backend-examples/express-resp-validation/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/usr/local/2019/openapi-backend-examples/express-resp-validation/node_modules/express/lib/response.js:267:15)
    at postResponseHandler (/usr/local/2019/openapi-backend-examples/express-resp-validation/index.js:61:30)
    at OpenAPIBackend.<anonymous> (/usr/local/2019/openapi-backend-examples/express-resp-validation/node_modules/openapi-backend/backend.js:247:90)
    at step (/usr/local/2019/openapi-backend-examples/express-resp-validation/node_modules/openapi-backend/backend.js:43:23)
    at Object.next (/usr/local/2019/openapi-backend-examples/express-resp-validation/node_modules/openapi-backend/backend.js:24:53)
    at fulfilled (/usr/local/2019/openapi-backend-examples/express-resp-validation/node_modules/openapi-backend/backend.js:15:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:39783) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:39783) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code..```

This does not happen if I have the operationId handler inside api.register()

So a couple of questions:
Does the  postResponseHandler applies to all of the endpoints like notFound or validationFail?
Does that error sound like a possible bug?

Thanks

Awesome package BTW! ๐Ÿ‘ 

Typescript types are too loose

A number of the type definitions are nullable for no reason I can discern. This is forcing me to write code like:

if (
  !apiContext ||
  !apiContext.validation ||
  !apiContext.validation.errors ||
  !apiContext.request
) {
  // Return a 500 error which will probably never actually happen
  return
}

// Otherwise continue with the handler

This is from a validationFail handler, but at least some similar checks might be needed in any handler. Is there any reason these things all need to be nullable?

Allow checking for Set-Cookie _response_ headers

I do response validation, and I want to make sure that when my login endpoint is responding with a successful http response code that it's setting at least one cookie.

I put this in my spec:

responses: {
    "204": {
        description: "success",
        headers: {
            "Set-Cookie": {
                description: "Cookie",
                schema: {
                    type: "string",
                    minLength: 1,

But validation always fails, despite the chrome inspector telling me that there were two "Set-Cookie" headers.

Here's the error from openid-backend:

{
    "keyword": "required",
    "dataPath": ".headers",
    "schemaPath": "#/properties/headers/required",
    "params": {
        "missingProperty": "set-cookie"
    },
    "message": "should have required property 'set-cookie'"
}

Support operations without operationId

We always assume each operation has an operationId. However, according to the OAS spec, it's not actually required. We should provide a fallback for these cases.

Paths should not match at / when apiRoot is set

The router does not enforce the presence of the apiRoot when matching the request with a route. For example, with apiRoot set to /v1 both requests /v1/my/operation and /my/operation will call the handler.

Prior to normalizing the path, the router should ensure that the prefix is found.

Dereference broken in v2.3.2

After d098d16 I can't reference spec files.

My directory structure

โ”œโ”€โ”€ lib
โ”‚ย ย  โ”œโ”€โ”€ index.js
โ”‚ย ย  โ””โ”€โ”€ lambda.js
โ”œโ”€โ”€ spec
โ”‚ย ย  โ”œโ”€โ”€ lambda.yml
โ”‚ย ย  โ””โ”€โ”€ openapi.yml
โ”œโ”€โ”€ test
โ”‚ย ย  โ””โ”€โ”€ authorizer.js
โ””โ”€โ”€ serverless.yml

In openapi.yml I have:

openapi: 3.0.1
info:
  title: lambda-api-name
  version: 1.0.0
paths:
  /thepath:
    $ref: './spec/lambda.yml'

And this was kind of weird because the reference was not relative to the openapi.yml document, but instead to the project root.

In index.js I'm loading the spec like this:

definition: path.resolve(__dirname, '../spec/openapi.yml'),

And this setup was working up until v2.3.1

Now I either get:

Error opening file "/the-path-to-lambda/spec/spec/lambda.yml"
in node_modules/json-schema-ref-parser/lib/resolvers/file.js:51:20

or if I update the reference to $ref: './lambda.yml' as it should be, I get:

Error opening file "/the-path-to-lambda/lambda.yml
in node_modules/json-schema-ref-parser/lib/resolvers/file.js:51:20

So I'm kind of stuck with this, I either have the path doubled spec/spec or no path at all.

openapi-schema-validation has been deprecated

According to the description here, the validator that is used in this library to perform schema validation has been deprecated. It would be great to change the dependencies to use its replacement, which is openapi-schema-validator.

Handling of '/' path

It looks like the router is not handling correctly empty paths, or path containing only /.
They get rewritten by an empty string, leading the operation matching to fail.

public normalizeRequest(req: Request): Request {
    return {
      ...req,
      path: (req.path || '') // path = '/' || ''
        .trim()
        .split('?')[0] // remove query string
        .replace(/^\/*/, '/') // add leading slash // path = '/'
        .replace(/\/+$/, ''), // remove trailing slash // path = ''
      method: req.method.trim().toLowerCase(),
    };
  }

Changing the line order like this seems to fix up the issue.

public normalizeRequest(req: Request): Request {
    return {
      ...req,
      path: (req.path || '') 
        .trim()
        .split('?')[0] // remove query string
        .replace(/\/+$/, '') // remove trailing slash
        .replace(/^\/*/, '/'), // add leading slash
      method: req.method.trim().toLowerCase(),
    };
  }

Server url

Consider the following spec:

openapi: "3.0.0"
servers:
  - url: http://localhost:8080/openapi
paths:
  /test:
    get:
      operationId: test
      responses:
        '200':
          description: OK

In the current state, running a query on

  • http://localhost:8080/test will return a 200 where a 404 was expected
  • http://localhost:8080/openapi/test will return a 404 instead of a 200.

This behaviour sounds wrong to me, but for a few reasons, I'm not sure whether openapi-backend should handle it or not, because in the event where more than one server is specified, without using the hostname, there can be ambiguous routes.
For instance, consider the following case:

openapi: "3.0.0"
servers:
  - url: http://domain2:8080/
  - url: http://domain1:8080/test
paths:
  /:
    get:
      operationId: test
      responses:
        '200':
          description: OK
  /test:
    get:
      operationId: test
      responses:
        '200':
          description: OK2

I believe either the following can be done:

  • Add a note in the docs, saying this is unsupported, leaving the responsibility of rewriting the path to the application.
  • Read the host header and use this to compute the appropriate path before matching. I'm not sure if this is going to work on every case, but it should I guess. If going down that road, I guess taking a parameter to enable/disable this behavior would also be a good idea.

I would love to hear your opinion about that.

Restrict to Node 8+ and use native async/await

I would like to restrict the library to support Node 8+ and configure TypeScript to use native async/await instead of down leveling it.

This gives two benefits:

  • much more pleasant debugging experience
  • smaller library size

Node 6 reaches end-of-life in April 2019 (~3 months from now), so it may be a good time to drop it.

What do you think?

implement/allow "required" attribute on response headers

Please add support for the "required" attribute in header specifications.

The spec:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#headerObject

says that header fields can contain (with exceptions) the same fields as parameters:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#parameterObject

Which includes "required" which is supposed to default to false.

openapi-backend does not allow the "required" attribute and acts as though it were set to "true".

Changing to the default specified in the spec would break backwards compatibility, but if that's a problem you could at least allow an honor the "required" attribute when it exists.

Multiple compilation errors in backend.d.ts and validation.d.ts

There seem to be problems in backend.d.ts that cause compilation errors when using this library from Typescript.

/path/to/project/node_modules/openapi-backend/backend.d.ts(1,8): error TS1192: Module '"/path/to/project/node_modules/openapi-backend/node_modules/ajv/lib/ajv"' has no default export.
/path/to/project/node_modules/openapi-backend/backend.d.ts(78,13): error TS2411: Property 'notFound' of type 'Handler | undefined' is not assignable to string index type 'Handler'.
/path/to/project/node_modules/openapi-backend/backend.d.ts(79,13): error TS2411: Property 'notImplemented' of type 'Handler | undefined' is not assignable to string index type 'Handler'.
/path/to/project/node_modules/openapi-backend/backend.d.ts(80,13): error TS2411: Property 'validationFail' of type 'Handler | undefined' is not assignable to string index type 'Handler'.
/path/to/project/node_modules/openapi-backend/validation.d.ts(1,8): error TS1192: Module '"/path/to/project/node_modules/openapi-backend/node_modules/ajv/lib/ajv"' has no default export.
TypeScript: 5 semantic errors

Is it possible to integrate `ajv-oai` in stead of `ajv`

Hello,

I'm in the process of do an investigation on how we can migrate from swaggerize-express to your implementation for OpenAPI 3.

Got these warnings in formats as an example:

unknown format "int64" ignored in schema at path "#/properties/path/properties/id"
unknown format "int64" ignored in schema at path "#/properties/path/properties/id"

Your project uses ajv to validate the validation of JSON, where https://github.com/BiteBit/ajv-oai validates also on the additional OpenAPI formats.

I'm not sure if this is a drop in replacement, but is it possible to integrate ajv-oai in stead of ajv ?

[Question] Automatically cleaning up values in postResponseHandler

Would you be able to recommend a method to effectively clean the response values using the schema? I would like to validate that a) the response is correct, b) the additional properties that would be present in the response are stripped.

I know that a) can already be handled. I'm just unsure how to proceed with B as I'd rather avoid building my own mechanism for cleaning up values based on the operation's response schema.

Thanks!

Crash on format field

format doesn't seem to be supported (spec says it can even be an arbitrary string):

(node:11785) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: unknown format "int64" is used in schema at path "#/properties/path/properties/customerId"

or

(node:12123) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: unknown format "password" is used in schema at path "#/properties/requestBody/allOf/1/properties/password"

Add endpoint to serve openapi definition

I would like to serve my openapi.yaml definition on /api-docs endpoint so I can use it in Swagger UI.

Using Express, I would do:
app.use('/api-docs', Express.static('openapi.yaml'));

Maybe we could use a new configuration property to support this new endpoint? Something like:

new OpenAPIBackend({
    definition: 'openapi.yaml',
    serveDefinition: '/api-docs',
    handlers: ...
  });

What do you think?

BTW, thanks for your great job ๐Ÿ‘

OpenAPI formats not supported?

I'm a bit confused regarding schema formats.
According to the Swagger OpenAPI 3.0 page, formats such as int32, byte etc are supported by OpenAPI 3.0:
Skรคrmbild frรฅn 2020-05-26 11-43-51

However, I cannot find these in the OpenAPI 3.0 schema itself at github.

Anyway, whenever my definitions make use of format for schemas, I get warnings from openapi-backend. Consider the following:

paths:
  /foo:
    post:
      operationId: foo
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                foo:
                  type: integer
                  format: int32
                bar:
                  type: string
                  format: byte         

Making a request to this operation renders this:

unknown format "int32" ignored in schema at path #/properties/requestBody/properties/foo
unknown format "byte" ignored in schema at path #/properties/requestBody/properties/bar

Should these formats be supported or ignored?

Header response validation

In #7, a mechanism to allow output validation was added using postResponseHandler. I like how its working since it let the responsibility to call validateResponse or not to the application.

In the OpenAPI specs, its also possible to define headers that we're expecting in the response.
I think it would make sense to add a validateResponseHeader method to the same location, but what are your thought on this?

I could work on a PR for it if you are interested.

API for validating data that doesn't originate in an HTTP request

Firstly, excellent library. I'm very optimistic about using it. I am integrating openapi-backend into a application rewrite at work. I can see how to set up validation for requests, but I would also like to do validation in the model for data that's generated internally, by another microservice, from a websocket connection, etc. My plan right now is to use ajv and get the schema from the openapi definition. Since openapi-backend already has the validation functions created for validating request payloads, I think it would be useful to have an API method to expose that validation functionality. It could accept the operationId and a payload, and return a validation result.

api.validateOperationBody(operationId, data)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.