jormaechea / open-api-mocker Goto Github PK
View Code? Open in Web Editor NEWA mock server based in OpenAPI Specification
Home Page: https://www.npmjs.com/package/open-api-mocker
License: MIT License
A mock server based in OpenAPI Specification
Home Page: https://www.npmjs.com/package/open-api-mocker
License: MIT License
An Open API is a public API. OpenAPI is a specification.
Could you take a look at this thing and try to get wording a bit consistent? :D https://github.com/openapi-contrib/glossary
I am trying to set up a mock with schema components separate in other yaml file and I'm getting errors.
[INFO ] < [400] {"errors":["can't resolve reference ../models/components.yml#/components/schemas/User from id #"]} (10 ms)
I make use of the docker image for the mock api.
I have this schema:
"schemas": {
"User": {
"type": "object",
"properties": {
"name": {
"type": "string",
"x-faker": "{{name.firstName}} {{name.lastName}}"
}
}
}
}
I get the following error using the 1.9.0 version:
Failed to generate fake result using {{name.firstName}} {{name.lastName}} schema. Falling back to primitive type.
However I get the correct result when I make use of the 1.8.0 version.
{camelCase} path params are not parsed correctly, nor are multiple params in the same path resulting in broken routes
When I request any mock path I get the following error:
TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token [""]
I'm using the following as the schema exported from Mockoon:
{
"openapi": "3.0.0",
"info": {
"title": "Centre Finder API",
"version": "1.0.0"
},
"servers": [
{
"url": "http://localhost:3000/api"
}
],
"paths": {
"/sites": {
"get": {
"description": "",
"responses": {
"200": {
"description": "Initial Response (With no params)",
"content": {},
"headers": {
"Access-Control-Allow-Origin": {
"schema": {
"type": "string"
},
"example": "*"
},
"Access-Control-Allow-Methods": {
"schema": {
"type": "string"
},
"example": "GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS"
},
"Access-Control-Allow-Headers": {
"schema": {
"type": "string"
},
"example": "Content-Type, Origin, Accept, Authorization, Content-Length, X-Requested-With"
},
"": {
"schema": {
"type": "string"
},
"example": ""
}
}
}
}
}
},
"/geolocation": {
"get": {
"description": "Google geolocation mock endpoint",
"responses": {
"200": {
"description": "",
"content": {},
"headers": {
"Access-Control-Allow-Origin": {
"schema": {
"type": "string"
},
"example": "*"
},
"Access-Control-Allow-Methods": {
"schema": {
"type": "string"
},
"example": "GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS"
},
"Access-Control-Allow-Headers": {
"schema": {
"type": "string"
},
"example": "Content-Type, Origin, Accept, Authorization, Content-Length, X-Requested-With"
},
"": {
"schema": {
"type": "string"
},
"example": ""
}
}
}
}
}
}
}
}
I have an issue where I want to provide an example for the documentation (when using Swagger UI), but I want the data the mock API responds with to be based on x-faker.
Schema:
"schemas": {
"User": {
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "John Doe",
"x-faker": "{{name.firstName}} {{name.lastName}}"
}
}
}
}
The Schema above will only show the example data and not the faker data. But the documentation will show correct data ("John Doe").
However if I remove the example, then I get correct faker data, but the documentation will only show "string" because that is the type.
Is it possible to change this method: https://github.com/jormaechea/open-api-mocker/blob/master/lib/response-generator/index.js#L40 to first check for x-faker instead of example? I guess that is where the issue is, but not sure.
We're having the following situation:
Property name
has an example
and an x-faker
extension. This leads to open-api-mocker giving example the higher priority. Therefore repetitions of that element via x-count
in an array all have "Desert Safari" as value.
Now it would be nice to be able to tell open-api-mocker to give x-faker
the higher priority in order to have different value for each element.
As soon as we remove example
it works like this - however we want to have the example value in the OpenAPI spec as well for documentation reasons.
Do you see any way to toggle the behaviour via command line switch for instance?
[FATAL] Error while validating schema: Expected a value of type
literal: "3.0.0"
but received"3.0.3"
. in openapi
You might want to allow patch versions.
https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
I am receiving an error from open-api-mocker when attempting to pass a request body that contains a parameter that is defined as array with items that are either a string or number.
The definition looks nearly identical to the example from the OpenAPI website:
# ["foo", 5, -2, "bar"]
type: array
items:
oneOf:
- type: string
- type: integer
When attempting to send a request where the value of this parameter is defined like this:
[1, 3, ">=5"]
open-api-mocker is responding with the following:
{
"errors": [
"Invalid request body: 'filters[0]' should be object"
]
}
I have done some debugging myself and have found that somewhere along the lines, the schema read from file is not quite what is sent through to ajv
to do the validation.
I am not familiar with superstruct
but I believe that it is it's use in lib/components/structs/schema.js that is causing the schema to become 'mangled' (I hesitate to say invalid since it passes the schema but messes up the intention).
Without knowing how superstruct
works, I am guessing that this block of code acts as a default object and incoming data gets assigned over the top of it.
Since the items
property is defined as items: struct.lazy(() => struct.optional(referenceUnion(SchemaStruct))),
(i.e. a Reference or a Schema, it validates against the same structure being defined in this file. This means that it uses the same default object which puts in an additional
type: object`.
This means the input schema above:
type: array
items:
oneOf:
- type: string
- type: integer
suddenly turns into this:
type: array
items:
type: object
# other default properties put in by superstruct default
oneOf:
- type: string
- type: integer
Whilst this is potentially valid in terms of the OpenAPI specification (I haven't checked using some other tool), it makes no sense since the array items can't be of type object and also use the anyOf, oneOf, allOf
keywords as well.
My initial thought on a fix would be to just remove the type from the default object but I have no idea on what other kind of effects that have.
It's been a while since I started developing OpenAPI Mocker.
It all started as a personal side-project, then we started to use it at work and recently caught the attention of many people as users and as contributors (thanks to every one of them).
So I think it's time to give some love to this project in the form of visual improvement, including a logo, a brand-new documentation site (already working on it using docusaurus), and who knows what else.
But as I have absolutely zero design skills, here I am asking for someone that would like to help me with their contributions.
Don't know if this will work, but it's worth the try.
Thanks again.
Joaquín.
💚
I'd like to specify a directory containing my definitions files and use it that way, is this possible?
[FATAL] Could not parse schema at /mnt/f/projects/x/src/main/resources/x_oas3.yaml: Unexpected characters ()
This is all I get. Sadly, I cannot provide the schema but other tools have no issues reading it. I can't find "unexpected characters" in the code - I'm curious where it comes from.
See the comment in #33
I'm not sure if this is a common use case but wanted to ask to see if this would be a useful feature. In my OpenAPI spec I have multiple example requests and corresponding responses for them. Would it make sense to match these by name so that a request which matches an example in the spec will look for a corresponding example response and return that? From my perspective it would be a better option than passing a Prefer
header to specify the desired response. Looking for feedback on this idea and if its popular I can attempt a PR.
OpenApiMocker
class options should be more explicit to ensure the object's interface with default values more easily.
This logic must be implemented in a new file to avoid adding complexity to main class.
Analyze CodeClimate issues and solve those considered worth it.
https://swagger.io/docs/specification/data-models/data-types/#pattern
name:
type: string
pattern: '^\d{3}-\d{2}-\d{4}$'
I have a string with pattern with the above schema, but it fails to parse the yaml
Error while validating schema: Expected a value of type
First of all, thanks for writing this. Excellent library!
Currently the code selects the first index in an array of examples, and I'm looking into implementing some sort of selection mechanism, similar to your Prefer
header for status codes. The use case being that some endpoints may give a variety of different responses for a 200, depending on user, role, or state.
Implementation seems trivial and I will gladly fork and PR the change, however if you have a specific implementation in mind, I'd like your input.
Decisions to make:
Thanks in advance!
Could we maybe get a tagged released of the roadmap/v2
branch? It has the updated version of Faker which would be quite useful, for me at least :)
Hello again, I come to you with another issue. I'm trying to test an operation with path parameters.
Source of the schema is here: https://github.com/bali182/oats/blob/mocker-example/projects/openapi-e2e-test/kitchenSink.json
When sending primitve type parameters (boolean, string, or number) its working as expected. However when I'm sending array or object parameters I get an error:
[INFO ] < [400] {
errors: [
"Invalid path param arrayInPath. Expected value of type array but received 'a,b'",
"Invalid path param objectInPath. Expected value of type object but received 's,str,b,false,n,1'",
],
}
For this URL: /path-params/foo/1/true/a,b/s,str,b,false,n,1
This is the relevant part of the schema:
{
"/path-params/{stringInPath}/{numberInPath}/{booleanInPath}/{arrayInPath}/{objectInPath}": {
"parameters": [
{
"name": "stringInPath",
...
},
{
"name": "numberInPath",
...
},
{
"name": "booleanInPath",
...
},
{
"name": "arrayInPath",
"required": true,
"in": "path",
"style": "simple",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
},
{
"name": "objectInPath",
"required": true,
"in": "path",
"style": "simple",
"schema": {
"type": "object",
"properties": {
"s": {
"type": "string"
},
"n": {
"type": "number"
},
"b": {
"type": "boolean"
}
}
}
}
],
"get": {
...
}
}
}
Now for serialization, I'm using the simple
method in this case described here:
https://swagger.io/docs/specification/serialization/
And I don't have explode
on which is the default.
Am I misunderstanding the parameter serialization or is the mocker library expecting path parameters differently?
Thank you,
Balazs
I do not have sudo privileges on my machine so I made a local bin at `` /home/anvib/centos ``` where npm is installed. The npm installation seems to work fine and install open-api-mocker, but running open-api-mocker crashes.
What else do I need?
[anvib@machine ~]$ cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
[anvib@machine ~]$
[anvib@machine ~]$
[anvib@machine ~]$
[anvib@machine ~]$ npm i -g open-api-mocker
/home/anvib/centos/usr/bin/open-api-mocker -> /home/anvib/centos/usr/lib/node_modules/open-api-mocker/lib/open-api-mocker-cli.js
/home/anvib/centos/usr/lib
└── [email protected]
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.3.1 (node_modules/open-api-mocker/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
[anvib@machine ~]$ open-api-mocker -h
/home/anvib/centos/usr/lib/node_modules/open-api-mocker/lib/open-api-mocker-cli.js:51
(async () => {
^
SyntaxError: Unexpected token (
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.runMain (module.js:611:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:160:9)
Hi there! I have my openapi yaml that has a snippet like this for the response
portion:
responses:
200:
description: Success
content:
text/html:
example: <form><input type="hidden" name="_csrf" value="5hchwoPz-Lx6J-naPVYQIwOrOgsM-lZXqzso" /></input><input type="hidden" name="transaction_id" value="CUUG6pIE" /><form/>
headers:
set-cookie:
schema:
type: string
example: "session ID cookie"
When I get the response it prints out escapes the quotes:
<form><input type=\"hidden\" name=\"_csrf\" value=\"5hchwoPz-Lx6J-naPVYQIwOrOgsM-lZXqzso\" /></input><input type=\"hidden\" name=\"transaction_id\" value=\"CUUG6pIE\" /><form/>
Perhaps I'm doing something wrong? Thanks for this tool and for any support!
How can I get a null
example value for a type string
? (while using OpenAPI 3.0.3)
"errorDescription" : {
"title" : "The errorDescription schema",
"type" : "string",
"nullable": true
}
When I use the example above, I get "errorDescription": "string",
as a result
When I add "default": null
there's a [FATAL] Error while mocking schema ...
(maybe updating ajv
is a solution? https://ajv.js.org/v6-to-v8-migration.html)
Let's say my operations look like this:
{
"/multiple-responses": {
"get": {
"operationId": "getWithMultipleResponses",
"responses": {
"200": {
"description": "Simple response returning a json object",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NamedSimpleObject"
}
}
}
},
"205": {
"description": "Simple response returning a json object",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NamedDeprecatedObject"
}
}
}
},
"default": {
"description": "Simple response returning a json object",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NamedComplexObject"
}
}
}
}
}
}
}
}
Is there a way to make the mock server respond with anything but 200?
引起这个问题的包是[email protected]
I have an enum of musical genres with approximately 200 entries:
I get this error:
server_mock | [INFO ] < [400] {"errors":["schema is invalid: data.properties['musicGenre'].enum should NOT have duplicate items (items ## 112 and 150 are identical)"]} (9 ms)
When reducing the number of items, the error is gone:
server_mock | [INFO ] > [OPTIONS] /users/78/preferences
server_mock | [INFO ] > [POST] /users/78/preferences
server_mock | [INFO ] < [201] null (173 ms)
Faker has lokale definitions that not all follow the ISO specifications. So de-DE definition for example is set with only 'de' not 'de_DE'.
I have an fix ready as pull request for you.
At current this project is designed to run as a standalone application through the use of the embedded express server.
There are use cases where this project could be beneficial to be used within an existing express application or be run in a serverless architecture where a server is not required.
I suggest that a new server type be added that is designed to be used when accessing open-api-mocker via package only (i.e. it would throw an error if used by the CLI). This would be very similar to the existing express server implementation but instead of the init
function starting up a server by listening on a port, a function is returned instead.
This function is then called in consuming code and is passed an existing express app.
Alternatively, one could pass the express app into the mock
method of OpenApiServer
.
It would look something like this:
// Consuming code in third party application
const app = express();
const server = new OpenApiMocker({
port: undefined,
server: "express-connector",
});
server.validate()
.then(() => server.mock())
.then((connect) => {
// The `init` method of the server (which is called in within the mock call above) returns a function that when called, adds the mocking functionality to the passed express app.
connect(app);
})
To avoid the consumer having to write their own code to handle watching the schema file for changes and attempting to reinitialise everything, I also propose a new "entry point" to be added as well that acts in a similar manner to the open-api-mocker-cli.js
file (and shares some code with it).
It would be used like this:
// Third party code
import connector from "open-api-mocker/express-connector";
import express from "express";
// or perhaps
// import express from "serverless-express/express";
const app = express(); // existing express app
const definitionFilePath = path.resolve(process.cwd(), "api-defs.yaml");
const { connect, schema } = connector({
schemaPath: definitionFilePath,
watch: process.env.NODE_ENV === "development",
});
connect(app)
.then(() => {
console.log("App connected successfully");
})
.catch((e) => {
console.error("Failed to connect mock API", e);
});
i would like by default for my mock to work with any extra query parameters specified in the URI, as long as path matches.
query fragments, or anything else after a ? character, shouldn't matter for the mock
in our case auth is done via query parameters so I cannot know at compile time the value of those parameters to mock it, they will change at runtime for every call, so best bet is to just ignore any query parameter and fragment by default if possible, maybe with just a configuration? is it possible now?
[INFO ] < [400] {"message":"Path not found: /test.com/apiproxy/21462/getAccountByEmail?sign=XXXX&timeStamp=1691594375028&token=ZZZZZZZ","paths":["POST /test.com/apiproxy/soa2/21462/batchMigrationForTravix","POST /apiproxy-test.com/apiproxy/soa2/21462/getAccountByEmail","POST /test.com/apiproxy/soa2/21462/getAccountByUid","POST /test.com/apiproxy/soa2/13861/verifyPassword","POST /test.com/apiproxy/soa2/13861/saveUserPassword","POST /test.com/apiproxy/soa2/13861/hasPassword","POST /test.com/apiproxy/soa2/11501/issueLoginSession","POST /test.com/apiproxy/soa2/11501/getContextByTicket","POST /test.com/apiproxy/soa2/11501/logoutByUid","POST /test.com/apiproxy/soa2/12809/createEmailAccount","POST /test.com/apiproxy/soa2/21462/bindEmail","POST /test.com/apiproxy/soa2/21462/bindThirdParty","POST /test.com/apiproxy/soa2/12809/disableUserByUid","POST /test.com/apiproxy/soa2/11838/saveUserInfo","POST /test.com/apiproxy/soa2/11838/getUserInfo"]} (26 ms)
The return value from parsePreferHeader
is { statuscode: '404' }
rather than { statusCode: '404' }
hence the following line does not pick it up correctly:
https://github.com/jormaechea/open-api-mocker/blame/7c0332c788f7af2f294fb6db46e3a75465f43e50/lib/mocker/express/server.js#L100
Since the faker package is no longer maintained after the maintainer went rogue and purposefully sabotaged it, I'd suggest switching over to the "official" replacement version which is @faker-js/faker (see the blog post here).
In doing so, we'll be open to getting the new features that exist in the new library and reduce the risk of accidentally upgrading to [email protected] which is the malicious version.
I am certainly happy to pick up this issue, ideally after #61 gets to avoid conflicts.
According to https://swagger.io/docs/specification/data-models/data-types OAS3 supports much more formats then actually provided. Those for numbers are missing completely and for strings only 'password' is 'ignored'.
"format is an open value, so you can use any formats, even not those defined by the OpenAPI Specification" (spec OAS3), so a more open solution would be nice.
I succest to implement an additional parameter, were you can pass a in additional formats. This formats should be added as additional formats for ajv. I Propose the following config payload:
[{
"type": "number" | "string",
"name": "customformatname",
"regex": "\\d*" //any js regex value is allowed to validate the custom format
}]
in the schema validator additional formats can then be added to ajv with the following code:
additionalConfig.formats.map(format =>
ajv.addFormat(format.name, {
type: format.type,
validate: (data => {
const regex = RegExp(format.regex);
const result = regex.test(data);
logger.debug(`${format.name} check for ${data} results with ${result}`);
return result;
})
})
);
I am receiving the following error when trying to make a call to the mock API using a request body that contains any number format:
type: object
properties:
branchId:
type: number
format: double # Any value here seems to cause an error
The error I am receiving is:
"unknown format "double" is used in schema at path "#/properties/branchId""
I have attempted to tried various combinations of type: number
and type: integer
against each of the number formats defined in the spec.
The spec also outlines that the format
field is optional and can take any value.
It seems wrong that this error is then occurring due to a field that is considered optional.
In terms of fixing this, I see that there is a line of code in the schema-valaidator that adds the password
format to the unknownFormats
array used by ajv, is it a case of just adding in all the recognised formats to that array (["int32", "int64", "float", "double", "byte", "binary", "date", "date-time", "password"]
)?
Whilst this would fix the problems for those schemas that use those default formats, any schema that uses (a completely valid) format that is not in that list will still throw this error. To prevent any further errors for formats, is it best to add some other kind of input to allow more unknown formats to be specified?
I was (unsuccessfully) trying to find if there's an option to generate incremental numbers that could be used in array values (be it an object or number literal directly)… essentially what you can do with counters in CSS.
Are you aware of a way to achieve / implement that?
Hi all,
I don't know if what I am asking is already present but I don't think so.
Could be helpful having a randomize string between a well defined array list.
For example inside openapi yaml something like this:
custom-mock: chooseOneBetween('string1', string2', 'string3')
Maybe is already implemented but googling I didn't find any solution.
Thanks,
A
I'm using an Apicurio edited OpenAPI 3.0x specification. When trying to load it, I get the error:
> open-api-mocker -s Playground.json
[FATAL] Error while validating schema: Expected a value of type `"get" | "post" | "put" | "patch" | "delete" | "options" | "head" | "trace"` for `/.description` but received `"description"`. in paths./.description
Hoever when looking at the specs, it is compliant. At the same level where the HTTP Verbs (get, post, put etc.) live, one can specify: summary
, description
or parameters
Example
{
"summary": "Path used to manage a single AutomationDefinition.",
"description": "The REST endpoint/path used to get, update, and delete single instances of an `AutomationDefinition`. This path contains `GET`, `PUT`, and `DELETE` operations used to perform the get, update, and delete tasks, respectively.",
"get": {
"tags": [
"Operations"
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AutomationDefinition"
}
}
},
"description": "Successful response - returns a single `AutomationDefinition`."
}
},
"operationId": "getAutomationDefinition",
"summary": "Get a AutomationDefinition",
"description": "Gets the details of a single instance of a `AutomationDefinition`."
},
"put": {
"requestBody": {
"description": "Updated `AutomationDefinition` information.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AutomationDefinition"
}
}
},
"required": true
},
"responses": {
"202": {
"description": "Successful response."
}
},
"operationId": "updateAutomationDefinition",
"summary": "Update a AutomationDefinition",
"description": "Updates an existing `AutomationDefinition`."
},
"delete": {
"responses": {
"204": {
"description": "Successful response."
}
},
"operationId": "deleteAutomationDefinition",
"summary": "Delete a AutomationDefinition",
"description": "Deletes an existing `AutomationDefinition`."
},
"parameters": [
{
"name": "automationdefinitionId",
"description": "A unique identifier for a `AutomationDefinition`.",
"schema": {
"type": "string"
},
"in": "path",
"required": true
}
]
}
Expected features:
master
branchTravis config file must be removed
It would be nice if the application returns the mocked data, taking into account the format parameter (if specified).
https://spec.openapis.org/oas/v3.1.0#dataTypeFormat
https://ajv.js.org/packages/ajv-formats.html#formats
Currently, type: string
is always returning 'string'
regardless of the specified format.
If the type is string and the format is date, a more appropriate response would be '2023-11-17'.
I am going to link a PR to this issue.
Thanks
Can I get the error from the API?
The API for example may return response of 200, 201 or 400. Can I mock the 201 and 400 as well?
Thanks.
I have an endpoint that will return a octet-stream as follows, but the response will be json instead of octet-stream
responses:
"200":
description: The requested properties are successfully returned.
content:
application/octet-stream:
schema:
type: string
format: binary
x-content-type: application/octet-stream
example: # Sample object
externalValue: '/Users/xxx/Downloads/nodejs-server-mock2/README.md'
With the above schema, the response is
curl -v -X GET "http://localhost:5000/api/objects" -H "accept: application/octet-stream" -H "X: fasdfa"
Note: Unnecessary use of -X or --request, GET is already inferred.
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 5000 (#0)
> GET /api/objects HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.64.1
> accept: application/octet-stream
> X-MSTR-ISERVER-SESSION: fasdfa
>
< HTTP/1.1 200 OK
< x-powered-by: jormaechea/open-api-mock
< Vary: Origin
< Access-Control-Allow-Credentials: true
< Content-Type: application/json; charset=utf-8
< Content-Length: 72
< ETag: W/"48-moCYJiPDoNqlzQ7AhOmaHZSX3cU"
< Date: Tue, 20 Apr 2021 00:52:10 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
{"externalValue":"/Users/xxx/Downloads/nodejs-server-mock2/README.md"}* Closing connection 0
schema
option to the OpenApiMocker
constructor to avoid calling setSchema()
later.watch
feature to the schema loadersRemoteSchemaLoader
Hello, I'm getting the error above, I'd like to ask for some help. I'm using a fairly simple schema, that can be found here:
https://github.com/bali182/oats/blob/master/projects/openapi-e2e-test/kitchenSink.json,
It has 1 operation, that looks like this, plus some schemas:
{
"/cat/dog": {
"get": {
"operationId": "getCatDog",
"parameters": [
{
"in": "query",
"schema": {
"type": "string"
},
"name": "foo"
}
],
"responses": {
"200": {
"description": "foo",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NamedSimpleObject"
}
}
}
}
}
}
}
}
And starting the mock API programmatically here:
https://github.com/bali182/oats/blob/master/projects/openapi-e2e-test/src/utils/getMockServer.ts
I see in the logs that it recognized the operation, but then fails with above mentioned error. Full stack:
[INFO ] Handling route GET /cat/dog
[INFO ] Mocking API at http://localhost:3000/
[INFO ] > [GET] /cat/dog?foo=test
TypeError: this._checkContentType is not a function
at D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\open-api-mocker\lib\mocker\express\request-handler.js:27:7
at Layer.handle [as handle_request] (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\layer.js:95:5)
at D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\index.js:335:12)
at next (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\index.js:275:10)
at rawParser (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\body-parser\lib\types\raw.js:67:7)
at Layer.handle [as handle_request] (D:\Code\oats\common\temp\node_modules.pnpm\[email protected]\node_modules\express\lib\router\layer.js:95:5)
Any clue if my schema is incorrect or it's something with the mock server?
When the response is a single number, its accidentally sent as status code, creating an invalid response which has an unexpected status and no body.
I have an OpenAPI spec (3.0) with an endpoint (simple get without parameters) using the following response:
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"type": "integer",
"example": 210
}
}
}
}
}
When accessing the endpoint, the response sent from the mock server uses the HTTP status 210 (instead of 200 as specified), and contains no body (instead of the expected number "210").
The following information is logged by the mock server:
[INFO ] > [GET] /demo
[WARN ] * Missing content-type header
[DEBUG] Searching first response
[INFO ] < [200] 210 (13 ms)
express deprecated res.send(status): Use res.sendStatus(status) instead ..\node_modules\open-api-mocker\lib\mocker\express\server.js:184:14
open-api-mock version: 1.11.0
The issue, as indicated by the logged message from the express server, seems to be caused by the invokation:
open-api-mocker/lib/mocker/express/server.js
Line 184 in 1101e9f
As per the express API spec, the body parameter can be "a Buffer object, a String, an object, Boolean, or an Array" (https://expressjs.com/en/4x/api.html#res.send). In this case however it's a number
, which apparently is used as status code due to the older/deprecated API.
So it should be ensured that the passed body is one of the listed types. A simple check like return res.send(typeof body === 'number' ? body.toString() : body);
is sufficient to fix the problem in the described case.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.