npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

api-schema-builder

v2.0.11

Published

build schema with validators for each endpoint

Downloads

185,164

Readme

api-schema-builder

NPM Version Build Status Coverage Status Known Vulnerabilities Apache 2.0 License

This package is used to build schema for input validation base on openapi doc Swagger (Open API) definition and ajv

Table of Contents

Install

npm install --save api-schema-builder

API

How to use

const apiSchemaBuilder = require('api-schema-builder');

api-schema-builder.buildSchemaSync(PathToSwaggerFile, options)

Synchronously build schema that would contain ajv validators for each endpoint, based on swagger definition.

The function returns schema object.

Arguments

  • PathToSwaggerFile – Path to the swagger definition
  • options – Additional options for build the schema.

Response

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 null
      • body:
        • validate: ajv validator that check: body only.
        • errors: in case of fail validation it return array of errors, otherwise return null
      • responses: 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 null
Options

Options 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}$/ }
    ]

api-schema-builder.buildSchema(jsonSchema, options)

Synchronously build schema that would contain ajv validators for each endpoint, based on given OpenAPI specification as json schema.

The function returns schema object.

api-schema-builder.buildSchema(PathToSwaggerFile, options)

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.

Usage Example

Validate request

  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;

Validate response

  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;

Important Notes

  • Objects - it is important to set any objects with the property 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
  • Response validator does not support readOnly attribute

Open api 3 - known issues

  • supporting inheritance with discriminator , only if the ancestor object is the discriminator.
  • The discriminator supports in the inheritance chain stop when getting to a child with no discriminator (a leaf in the inheritance tree), meaning a leaf can't have a field which starts a new inheritance tree. so child with no discriminator cant point to other child with discriminator,
  • Response validator support only application/json content type
  • Response validator does not support links and writeOnly attribute

Running Tests

Using mocha and istanbul

npm run test