@ehuelsmann/openapi-validator
v0.17.1
Published
Common code for jest-openapi and Chai OpenAPI Response Validator
Maintainers
Readme
OpenAPI Validator
Note This project is a fork from the openapi-library project because that project is not maintained at the moment. This project contains updates and security fixes, but ideally will be merged back into that project, as soon as it's maintained again.
Common code for @ehuelsmann/jest-openapi and Chai OpenAPI Response Validator
Contributing ✨
If you've come here to help contribute - thanks! Take a look at the contributing docs to get started.
Installation
npm install --save-dev @ehuelsmann/openapi-validatoryarn add --dev @ehuelsmann/openapi-validatorImporting
This package ships with both ESM (preferred) and CommonJS builds, so it works in any environment.
ESM / TypeScript
import { makeApiSpec, makeResponse } from '@ehuelsmann/openapi-validator';CommonJS / JavaScript
const { makeApiSpec, makeResponse } = require('@ehuelsmann/openapi-validator');Usage
This package provides the shared validation logic used by @ehuelsmann/jest-openapi and @ehuelsmann/chai-openapi-response-validator. Use it to build your own OpenAPI validation integration.
Loading an OpenAPI spec
makeApiSpec accepts either an absolute filepath or an object representing an OpenAPI (v2 or v3) document:
import { makeApiSpec } from '@ehuelsmann/openapi-validator';
// From an absolute filepath (YAML or JSON)
const spec = makeApiSpec('/absolute/path/to/openapi.yml');
// From an object
const spec = makeApiSpec({
openapi: '3.0.0',
info: { title: 'Example API', version: '1.0.0' },
paths: {},
});Validating a response
makeResponse wraps an HTTP response from axios, supertest, superagent, or chai-http so it can be validated against the loaded spec:
import { makeApiSpec, makeResponse } from '@ehuelsmann/openapi-validator';
const spec = makeApiSpec('/absolute/path/to/openapi.yml');
// res is an axios, supertest, superagent, or chai-http response object
const response = makeResponse(res);
const validationError = spec.validateResponse(response);
if (validationError) {
throw new Error(validationError.message);
}