1.0.0 • Published 2 years ago

@undabot.com/open-api-payload-validator v1.0.0

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
2 years ago

@undabot.com/open-api-payload-validator

Validates the request body of HTTP requests using OpenAPI document in JSON format.

Installation

npm install @undabot.com/open-api-payload-validator --save
npm install ajv@^8 --save

ajv is an optional dependecy, but strongly recommended for those unfamiliar with this library.

Usage

Setup

Given the OpenAPI document for a specific API, instantiate the validator.

import Ajv from 'ajv';
import { PayloadValidator } from '@undabot.com/open-api-payload-validator';

const openApiJsonDocument = {
  paths: {
    '/user': {
      post: {
        // ...
      },
      patch: {
        // ...
      },
    },
    '/post/{postId}/comment': {
      post: {
        // ...
      },
    },
  },
};

const MyApiValidator = new PayloadValidator({
  document: openApiJsonDocument,
  schemaValidator: new Ajv(),
});

When using the ajv, you are free to configure it's behaviour during instantiation through it's constructor arguments.

Validate

Validate the request body before sending a request.

Example: Create user

function createUser(createUserDto) {
  const errors = MyApiValidator.validate(
    'post:application:json:/user',
    createUserDto
  );

  if (errors) {
    console.log(errors);
    return;
  }

  return fetch('https://example.com/user', {
    body: JSON.stringify(createUserDto),
    method: 'POST',
    headers: {
      'CONTENT-TYPE': 'application/json',
    },
  });
}

Example: Update user

function updateUser(updateUserDto) {
  const errors = MyApiValidator.validate(
    'patch:application:json:/user/{userId}',
    userData
  );

  if (errors) {
    console.log(errors);
    return;
  }

  return fetch('https://example.com/user', {
    body: JSON.stringify(updateUserDto),
    method: 'PATCH',
    headers: {
      'CONTENT-TYPE': 'application/json',
    },
  });
}

Example: Submit comment

function submitComment(postId, commentDto) {
  const errors = MyApiValidator.validate(
    'post:application:json:/post/{postId}/comment',
    commentDto
  );

  if (errors) {
    console.log(errors);
    return;
  }

  return fetch(`https://example.com/post/${postId}/comment`, {
    body: JSON.stringify(commentDto),
    method: 'POST',
    headers: {
      'CONTENT-TYPE': 'application/json',
    },
  });
}

API

new PayloadValidator({document: JsonObject | string, schemaValidator: Ajv}): PayloadValidator

The document argument must be an OpenAPI document with paths object defined.

The schemaValidator argument must be an instance of Ajv class.

PayloadValidator.validate(identifier: string; data: JsonObject | string): null | ErrorObject[]

The identifier argument is a string used for identifing the correct schema. It has a following format: <method>:<media-type>:<path>. An example: post:application/json:/post/{postId}/comment.

If the corresponding schema is not found, an error is thrown.

The data argument is a JSON object (serialized or deserialized). It can also be refered to as a JSON:Schema instance.

The return type depends on the validity of data argument (the JSON:Schema instance). If the data instance isn't valid, ErrorObject[] is returned, otherwise, null is returned.

makeSchemaList(document: JsonObject | string ): {JsonSchema}[]

makeSchemaList is used by the PayloadValidator internally, but it is also available for use externally.

The return type is an array of JsonSchema, the JSON:Schema document.