Giter Site home page Giter Site logo

waleedashraf / asyncapi-validator Goto Github PK

View Code? Open in Web Editor NEW
43.0 5.0 10.0 1.77 MB

Message validator for Kafka/RabbitMQ/Anything through AsyncAPI schema

Home Page: https://www.npmjs.com/package/asyncapi-validator

License: MIT License

JavaScript 100.00%
asyncapi asyncapi-specification api kafka rabbitmq validator openapi

asyncapi-validator's Introduction

Unit Tests codecov CodeQL

asyncapi-validator

Message validator through AsyncAPI schema

_Note: This package only support AsyncAPI Schema v2.0.0 and above. Since v3.0.0, support for older versions of AsyncAPI Schema has been removed.

npm i asyncapi-validator

Features

  • Validate your messages against your AsyncApi Document
  • Validate your AsyncApi Document against AsyncApi Schema definition
  • Load your AsyncApi Schema from local file or any URL
  • Supports AsyncApi in JSON and YAML format
  • Supports AsyncAPI v2.0.0 and above

Content

Class Methods

AsyncApiValidator.fromSource()

/** 
 * Load and Parse the schema from source.
 * @param {string | Object} source - local PATH or URL of schema or schema Object
 * @param {Object} options - options for validation
 * @returns {Promise}
 */
AsyncApiValidator.fromSource(source, options)

Options

value type description
ignoreArray boolean optional If true, then if schema is defined as an array and payload is an object, then payload will be placed inside an array before validation.
msgIdentifier string optional (required only if you use .validate() method) Name of the parameter whose value will be used as "key" in .validate() method. Recommendation is to use "name" as described in message-object. You can also use Specification Extensions.
path string optional Path to the AsyncAPI document. It will be used to resolve relative references. Defaults to current working dir. As used in asyncapi-parser

Instance Methods / Properties

.validateByMessageId()

Here messageId should be as defined in AsyncAPI Schema v2.4.0. To use this method, your AsyncAPI Schema version should be >= v2.4.0.

/**
 * Method to validate the Payload against schema definition.
 * @param {string} key - required - messageId
 * @param {Object} payload - required - payload of the message
 * @returns {boolean}
 */
.validateByMessageId(key, payload)

.validate()

To use this method for validation, you should provide msgIdentifier in AsyncApiValidator options.

/**
 * Method to validate the Payload against schema definition.
 * @param {string} key - required - message key
 * @param {Object} payload - required - payload of the message
 * @param {string} channel - required - name of the channel/topic
 * @param {string} operation - required - publish | subscribe
 * @returns {boolean}
 */
.validate(key, payload, channel, operation)

.schema

.schema property can be used to access AsyncAPI schema in JSON format and with all the refs resolved.

Example usage with .validateByMessageId() method

Schema

asyncapi: 2.4.0

info:
  title: User Events
  version: 1.0.0

channels:
  user-events:
    description: user related events
    publish:
      message:
        messageId: UserRemoved
        payload:
          type: object
          properties:
            userEmail:
              type: string
            userId:
              type: string
const AsyncApiValidator = require('asyncapi-validator')
let va = await AsyncApiValidator.fromSource('./api.yaml')

// validate messageId 'UserRemoved'
va.validateByMessageId('UserRemoved', {
  userId: '123456789',
  userEmail: '[email protected]',
})

Example usage with .validate() method

Schema

asyncapi: 2.0.0

info:
  title: User Events
  version: 1.0.0

channels:
  user-events:
    description: user related events
    publish:
      message:
        name: UserDeletedMessage
        x-custom-key: UserDeleted
        payload:
          type: object
          properties:
            userEmail:
              type: string
            userId:
              type: string
const AsyncApiValidator = require('asyncapi-validator')
let va = await AsyncApiValidator.fromSource('./api.yaml', {msgIdentifier: 'x-custom-key'})

// validate 'UserDeleted' on channel 'user-events' with operation 'publish'
va.validate('UserDeleted', {
  userId: '123456789',
  userEmail: '[email protected]',
}, 'user-events', 'publish')

In above example, "msgIdentifier" is "x-custom-key". That is why, "UserDeleted" is used as "key" in "va.validate()" method.

Errors

Error thrown from asyncapi-validator will have these properties.

key type value description
name string AsyncAPIValidationError AsyncAPIValidationError
key string "key" of payload against which schema is validated
message string errorsText from AJV
errors array Array of errors from AJV

Error Example

{
  AsyncAPIValidationError: data.type must be equal to one of the allowed values at MessageValidator.validate (.....
  name: 'AsyncAPIValidationError',
  key: 'hello',
  errors:
    [
      { keyword: 'enum',
        dataPath: '.type',
        schemaPath: '#/properties/type/enum',
        params: [Object],
        message: 'must be equal to one of the allowed values'
      }
    ]
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.