Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@brightcove/openapi-validator

Package Overview
Dependencies
Maintainers
0
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@brightcove/openapi-validator

Provides Express middleware for routes based on an OpenAPI spec

  • 5.0.3
  • unpublished
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

OpenAPI Validator

package-info NPM NodeJS Build Status

This provides Express middleware to validate routes based on an OpenAPI spec

Installation

  1. Make sure you have a .npmrc file with the proper auth token
  2. npm install @brightcove/openapi-validator

Pre-parsing YAML files

If you pass in a path to a YAML file, the library will parse it on initialization into JSON. For particularly large YAML files, this can lead to slow startup times, so the library offers the ability to pre-parse YAML files.

npx @brightcove/openapi-validator parse
Command List

  help      help
  parse     parses all YAML files in the specified folder into JSON

Options

  -i, --import    Folder path to read YAML files from (default: "api")
  -e, --export    Folder path to export JSON files to  (default: "api")

Initialization

The library needs to be initialized with the path to a valid YAML and/or JSON file.

const path = require('path');
const { OpenAPIValidator } = require('@brightcove/openapi-validator');

const yamlPath = path.join(__dirname, '../../api/index.yaml');
const jsonPath = path.join(__dirname, '../../api/index.json');
const app = express();

OpenAPIValidator.add("my api", yamlPath, jsonPath);
app.use(OpenAPIValidator.init());

const { validator, validateRequest, addResponseValidation, docs, schema } = OpenAPIValidator.api("my api");

Note: If there is only a single API added, calling OpenAPIValidator.api() without a name will retrieve it.

Options

The following fields can be set when calling OpenAPIValidator.add()

FieldTypeDescriptionRequired
nameStringName used to retrieve the APIyes
yamlPathStringPath to the OpenAPI YAML fileyes, to view docs, or jsonPath must be included
jsonPathStringPath to the OpenAPI JSON fileyes, or yamlPath must be included
hostStringThe server host. This is used for the documentation middleware if static assets are behind a CDNno
emptyRequestValidBooleanDetermines whether empty request bodies, for requests with required: true and no required properties, are considered valid. By default this is true.no
errorCodesObjectAllows overriding of the default error code valuesno
errorCodes.InputValidationErrorStringOverrides the InputValidationError code. By default it is "400.00".no
errorCodes.OutputValidationErrorStringOverrides the OutputValidationError code. By default it is "500.00".no
docsPageTitleStringThe desired page title for the documentation route page. Otherwise the title will be "{name} Reference"no

Validate Requests

Manual

const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { validator } = OpenAPIValidator.api("my api");

router.post('/my/test/route', (req, res) => {
  const { valid, errors } = validator.validateRequest(req);
});

Middleware

The validateRequest middleware needs to be added to the specific route that needs validation before the route handler. If the middleware isn't added to the specific route, it will not function properly.

Any errors will be forwarded to the configured error handler as an InputValidationError object.

const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { validateRequest } = OpenAPIValidator.api("my api");

router.post('/my/test/route', validateRequest, (req, res) => { ... });

router.use((err, req, res, next) => {
  // err will be an `InputValidationError`
});

Validate Responses

Manual

const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { validator } = OpenAPIValidator.api("my api");

router.post('/my/test/route', (req, res) => {
  const { valid, errors } = validator.validateResponse(req, statusCode, contentType, body);
});

Middleware

Automatic validation requires the middleware addResponseValidation which adds the validate() function to the res object. If the middleware isn't added to the specific route, it will not function properly.

This function will validate the response and will prevent data from being returned to the client if it fails.

Any errors will be forwarded to the configured error handler as an OutputValidationError object.

const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { addResponseValidation } = OpenAPIValidator.api("my api");

router.post('/my/test/route', addResponseValidation, (req, res) => {
  ...
  const body = { "status": "success" };
  res.validate().status(200).send(body);
});

router.use((err, req, res, next) => {
  // err will be an `OutputValidationError`
});

Caveats

  • anyOf and oneOf aren't properly validated, so it's suggested to avoid these and have the logic for validation elsewhere
  • Nested schema refs will allow additional properties unless explicitely given additionalProperties: false
  • Deeply nested schema in arrays don't seem to be properly validated

JSON Schema

To view the JSON schema representation of the YAML file, you can use the following middleware

const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { schemaRoute } = OpenAPIValidator.api("my api");

app.use('/schema', schemaRoute());

Documentation

To view a Swagger UI render of the OpenAPI spec, you can use the following middleware

const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { docsRoute } = OpenAPIValidator.api("my api");

app.use('/docs', docsRoute());

FAQs

Package last updated on 29 Apr 2024

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc