Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
api-schema-builder
Advanced tools
This package is used to build schema for input validation base on openapi doc Swagger (Open API) definition and ajv
Table of Contents
npm install --save api-schema-builder
const apiSchemaBuilder = require('api-schema-builder');
Synchronously build schema that would contain ajv validators for each endpoint, based on swagger definition.
The function returns schema object.
PathToSwaggerFile
– Path to the swagger definitionoptions
– Additional options for build the schema.Array that contains:
path_name
: the paths it written in the api doc, for example /pet
.
method
: the relevant method it written in the api doc, for example get
.
parameters
:
validate
: ajv validator that check: paths, files, queries and headers.errors
: in case of fail validation it return array of errors, otherwise return nullbody
:
validate
: ajv validator that check: body only.errors
: in case of fail validation it return array of errors, otherwise return nullresponses
: contain array of statusCodes
statusCode
:
validate
: ajv validator that check body and headers.errors
: in case of fail validation it return array of errors, otherwise return nullOptions currently supports:.
keywords
- Array of keywords that can be added to ajv
configuration, each element in the array can be either an object or a function.
If the element is an object, it must include name
and definition
. If the element is a function, it should accept ajv
as its first argument and inside the function you need to call ajv.addKeyword
to add your custom keyword
makeOptionalAttributesNullable
- Boolean that forces preprocessing of Swagger schema to include 'null' as possible type for all non-required properties. Main use-case for this is to ensure correct handling of null values when Ajv type coercion is enabled
ajvConfigBody
- Object that will be passed as config to new Ajv instance which will be used for validating request body. Can be useful to e. g. enable type coercion (to automatically convert strings to numbers etc). See Ajv documentation for supported values.
ajvConfigParams
- Object that will be passed as config to new Ajv instance which will be used for validating request headers and parameters. See Ajv documentation for supported values.
contentTypeValidation
- Boolean that indicates if to perform content type validation in case consume
field is specified and the request body is not empty.
expectFormFieldsInBody
- Boolean that indicates whether form fields of non-file type that are specified in the schema should be validated against request body (e. g. Multer is copying text form fields to body)
buildRequests
- Boolean that indicates whether if create validators for requests, default is true.
buildResponses
- Boolean that indicates whether if create validators for responses, default is false.
basePath
- Base path of the external definition files referenced in the given schema. This is required whenever passing json schema instead of PathToSwaggerFile
to the constructor or the external files are not stored in the same path of PathToSwaggerFile
formats
- Array of formats that can be added to ajv
configuration, each element in the array should include name
and pattern
.
formats: [
{ name: 'double', pattern: /\d+\.(\d+)+/ },
{ name: 'int64', pattern: /^\d{1,19}$/ },
{ name: 'int32', pattern: /^\d{1,10}$/ }
]
Synchronously build schema that would contain ajv validators for each endpoint, based on given OpenAPI specification as json schema.
The function returns schema object.
Asynchronously build schema that would contain ajv validators for each endpoint, based on swagger definition.
The function returns Promise that resolves with a schema object.
s
Arguments, options and response are the same as for the buildSchemaSync
method.
const schema = apiSchemaBuilder.buildSchemaSync('test/unit-tests/input-validation/pet-store-swagger.yaml');
let schemaEndpoint = schema['/pet']['post'];
//validate request's parameters
let isParametersMatch = schemaEndpoint.parameters.validate({ query: {},
headers: { 'public-key': '1.0'},path: {},files: undefined });
expect(schemaEndpoint.parameters.errors).to.be.equal(null);
expect(isParametersMatch).to.be.true;
//validate request's body
let isBodysMatch =schemaEndpoint.body.validate({'bark': 111});
expect(schemaEndpoint.body.errors).to.be.eql([{
'dataPath': '.bark',
'keyword': 'type',
'message': 'should be string',
'params': {
'type': 'string'
},
'schemaPath': '#/properties/bark/type'}
])
expect(isBodysMatch).to.be.false;
const schema = apiSchemaBuilder.buildSchemaSync('test/unit-tests/input-validation/pet-store-swagger.yaml');
let schemaEndpoint = schema['/pet']['post'].responses['201'];
//validate response's body and headers
let isValid = schemaEndpoint.validate({
body :{ id:11, 'name': 111},
headers:{'x-next': '321'}
})
expect(schemaEndpoint.errors).to.be.eql([
{
'dataPath': '.body.name',
'keyword': 'type',
'message': 'should be string',
'params': {
'type': 'string'
},
'schemaPath': '#/body/properties/name/type'
}])
expect(isValid).to.be.false;
type: object
inside your swagger file, although it isn't a must in the Swagger (OpenAPI) spec in order to validate it accurately with ajv it must be marked as object
Using mocha and istanbul
npm run test
2.0.0 - 23 April, 2020
api-schema-builder
and reduce total bundle size by removing polyfills #45FAQs
build schema with validators for each endpoint
The npm package api-schema-builder receives a total of 18,897 weekly downloads. As such, api-schema-builder popularity was classified as popular.
We found that api-schema-builder demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.