payu / api-schema-builder Goto Github PK
View Code? Open in Web Editor NEWLicense: Apache License 2.0
License: Apache License 2.0
This code in open-api3.js
const requestPath = `paths[${currentPath}][${currentMethod}].requestBody.content[${contentType}].schema`;
const dereferencedBodySchema = get(dereferenced, requestPath);
const referencedBodySchema = get(referenced, requestPath);
assumes that request body content definition is always given inline within Operation Object's requestBody field (since it is expected to be found in referenced schema), while by OpenAPI 3 definition there can be a reference as well.
For example:
/path:
post:
requestBody:
$ref: '#/components/requestBodies/Body'
components:
requestBodies:
Body:
required: true
content:
'application/json':
schema:
$ref: '#/components/schemas/BodySchema'
For such schema body validation set is empty. Please correct this.
We created a custom format
for phone numbers. As it is a function and not a regexp, I tried to pass it to Ajv via the following options:
this.validator = buildSchemaSync(this.spec, {
ajvConfigParams: {
formats: {
email: emailValidator.validate,
phone: phoneValidator.validate, // <-
},
},
})
For request parameters, this is working fine, but when I validate arequest body with this format, it failing with the following message:
Error: unknown format "phone" is used in schema at path "#/anyOf/1/properties/phoneNumber"
for example : int32, double timestamp
now it build schema asynchronies way
It seems that exclusiveMaximum and exclusiveMinimum are not properly supported by the package.
According to OpenApi specs both exclusiveMaximum and exclusiveMinimum should be boolean, but when passing the below property definition it throws an error
exchange_rate:
type: number
format: double
minimum: 0
exclusiveMinimum: true
properties['exchange_rate'].exclusiveMinimum should be number
this is because according to the json schema specs exclusiveMaximum and exclusiveMinimum should be passed as a number
https://json-schema.org/understanding-json-schema/reference/numeric.html#range
An approach to investigating missing swagger features is a good question.
Suggested reading:
Those are probably the core features that related to input validation.
The approach could be: start writing tests for each of the keywords and see the behavior, In case it is not as expected, we can open an issue and fix it.
Maintaining the current code-base is quite hard we should consider refactoring it, maybe also use Typescript while doing so.
When using relative server urls in OpenAPI 3.0 like shown:
"servers": [
{
"url": "/api/foo"
}
]
An error is thrown:
TypeError [ERR_INVALID_URL]: Invalid URL: /api/foo
Stack trace points to the error occurring here. It seems that all values in the url
field are assumed to be complete urls. Is there some way we can check for a relative url before passing to the URL
constructor?
under responses[statusCode] will be
{
validator,
errors,
headers : {validator, errors}
body: {validator, errors}
}
const schema = await apiSchemaBuilder.buildSchema(
path.join(__dirname, './openapi.json'),
{
buildResponses: true,
}
);
in index.d.ts file change the return object from Promise to Promise
and add interface of validatorSchema
How do I extend ajv
with custom packages, eg https://github.com/ajv-validator/ajv-keywords
?
I don't see how I can grab the ajv
instance to enable something like this:
require('ajv-keywords')(ajv);
ajv.validate({ instanceof: 'RegExp' }, /.*/); // true
ajv.validate({ instanceof: 'RegExp' }, '.*'); // false
It doesn't look like I can trigger this via the ajvConfigBody
options for example.
Thanks!
use plugin of chai\should
or use a function that everybody call
can be refactor by script
In order to support PayU/openapi-validator-middleware#80, we need to allow this behavior in api-schema-builder
Unlike swagger-parser
, js-yaml
doesn't perform any OpenAPI document validation.
We should consider adding https://www.npmjs.com/package/openapi-schema-validator.
This would be a breaking change.
in case of ajv error it return it under the schema endpoint, instead should return array of errors in case of validaiton fail. in case of success validation return empty array.
example:
let validationErrors = schemaEndpoint.parameters.validate({ query: {},
headers: { 'host': 'test' },
path: {},
files: undefined });
expect(validationErrors).to.be.eql([
{
'dataPath': '.headers',
'keyword': 'required',
'message': "should have required property 'api-version'",
'params': {
'missingProperty': 'api-version'
},
'schemaPath': '#/properties/headers/required'
}
]);
Please lazy load parsers import based on the submitted schema at run time.
api-schema-builder/src/index.js
Line 8 in 784c5ad
Currently i'm using for Openapi v2 but v3 parsers are getting loaded.
I'd like to be able to set options for swagger-parser
(https://apitools.dev/swagger-parser/docs/options.html). Is that possible? I don't see where to do that.
Great tool. Thanks.
Hi! π
Firstly, thanks for your work on this project! π
Today I used patch-package to patch [email protected]
for the project I'm working on.
Here is the diff that solved my problem:
diff --git a/node_modules/api-schema-builder/src/parsers/open-api3.js b/node_modules/api-schema-builder/src/parsers/open-api3.js
index c0665d6..f4c2cf0 100644
--- a/node_modules/api-schema-builder/src/parsers/open-api3.js
+++ b/node_modules/api-schema-builder/src/parsers/open-api3.js
@@ -17,13 +17,13 @@ module.exports = {
};
function buildRequestBodyValidation(dereferenced, referenced, currentPath, currentMethod, options) {
- const contentTypes = get(dereferenced, `paths[${currentPath}][${currentMethod}].requestBody.content`);
+ const contentTypes = get(dereferenced, `paths['${currentPath}']['${currentMethod}'].requestBody.content`);
if (!contentTypes) {
return;
}
// Add default validator for default content type for compatibility sake
- const requestPath = `paths[${currentPath}][${currentMethod}].requestBody.content[${schemaUtils.DEFAULT_REQUEST_CONTENT_TYPE}].schema`;
+ const requestPath = `paths['${currentPath}']['${currentMethod}'].requestBody.content['${schemaUtils.DEFAULT_REQUEST_CONTENT_TYPE}'].schema`;
const dereferencedBodySchema = get(dereferenced, requestPath);
const referencedBodySchema = get(referenced, requestPath);
@@ -37,7 +37,7 @@ function buildRequestBodyValidation(dereferenced, referenced, currentPath, curre
// Add validators for all content types
const schema = Object.keys(contentTypes).reduce((result, contentType) => {
- const requestPath = `paths[${currentPath}][${currentMethod}].requestBody.content[${contentType}].schema`;
+ const requestPath = `paths['${currentPath}']['${currentMethod}'].requestBody.content['${contentType}'].schema`;
const dereferencedBodySchema = get(dereferenced, requestPath);
const referencedBodySchema = get(referenced, requestPath);
@@ -55,7 +55,7 @@ function buildRequestBodyValidation(dereferenced, referenced, currentPath, curre
}
function buildResponseBodyValidation(dereferenced, referenced, currentPath, currentMethod, statusCode, options) {
- const contentTypes = get(dereferenced, `paths[${currentPath}][${currentMethod}].responses[${statusCode}].content`);
+ const contentTypes = get(dereferenced, `paths['${currentPath}']['${currentMethod}'].responses['${statusCode}'].content`);
if (!contentTypes) {
return;
}
@@ -135,7 +135,7 @@ function handleSchema(data) {
}
function buildHeadersValidation(responses, statusCode, { ajvConfigParams, formats, keywords, contentTypeValidation }) {
- const headers = get(responses, `[${statusCode}].headers`);
+ const headers = get(responses, `['${statusCode}'].headers`);
if (!headers) return;
const defaultAjvOptions = {
This issue body was partially generated by patch-package.
after loading swagger in synchronise way, can remove buildValidations
from exports
lodash.get is used here : https://github.com/PayU/api-schema-builder/blob/master/src/index.js#L2
and it's not mentioned in package.json dependencies.
Currently when defining objects with oneOf, anyOf or allOf both readOnly and writeOnly logic doesn't work at all.
Example:
AnyOf:
anyOf:
- $ref: '#/components/schemas/User'
- type: object
required:
- additionalOneOfField
properties:
additionalOneOfField:
type: string
Since swagger-parse supports synchronous loading, there are no reasons to use async mode anymore.
See: https://swagger.io/docs/specification/data-models/data-types/#nullable
OpenApi allows a property to be explicitly set to nullable: true
. This means that it can be required but allow an explicit value of null
. Currently this is not respected by this validator.
Hi,
I use Swagger client (https://github.com/swagger-api/swagger-js) to talk to API, but it doesn't provide response validation. An instance of Swagger client already has an object representing the spec.
Is it possible to use api-schema-builder in the browser, passing it the spec from Swagger client?
Do you think it's possible to upgrade swagger-parser dependency to get rid of this warning?
warning api-schema-builder > swagger-parser > z-schema > [email protected]: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
z-schema upgraded core-js to v3 (3.2.1) in 4.1.1 and swagger-parser uses this since 8.0.1.
z-schema dropped core-js since 4.2.0 and swagger-parser upgraded to it in 8.0.4.
master
branch failed. π¨I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iβm sure you can fix this πͺ.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here are some links that can help you:
If those donβt help, or if this issue is reporting something you think isnβt right, you can always ask the humans behind semantic-release.
An npm token must be created and set in the NPM_TOKEN
environment variable on your CI environment.
Please make sure to create an npm token and to set it in the NPM_TOKEN
environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/
.
Good luck with your project β¨
Your semantic-release bot π¦π
I have the following definition:
- in: query
name: ids
type: array
uniqueItems: true
collectionFormat: csv
required: true
minItems: 1
items:
type: string
description: A comma-separated list of ids, as a string
The validator only seems to check that the parameter is present, but will not check if it is empty or if the number of items matches when it is present but no value is assigned.
On top of these changes https://github.com/ajv-validator/ajv/blob/master/docs/v6-to-v8-migration.md I also saw that some of the validation error messages are changed.
i.e
- "message": "must match format \"abcName\""
+ "message": "should match format \"abcName\""
recover by
add reference that does not exist in the swagger
const basePaths = dereferenced.servers && dereferenced.servers.length
? dereferenced.servers.map(({ url }) => new URL(url).pathname)
: [dereferenced.basePath || '/'];
Object.keys(dereferenced.paths).forEach(currentPath => {
dereferenced variable content will have the error details, so dereferenced.paths will be undefined.
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.