Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including asyncapi-validator with all npm packages installed. Try it out:

var asyncapiValidator = require("asyncapi-validator")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

asyncapi-validator v2.4.5

message validator through asyncapi schema

Unit Tests codecov CodeQL

asyncapi-validator

message validator through asyncapi schema

Note: This library works with v2 of AsyncAPI Schema. Support for v1 is deprecated and will be removed in next major version.

npm i asyncapi-validator

Features

  • Validate your AsyncApi Schema against AsyncApi Schema definition
  • Validate your messages against your AsyncApi Schema definition
  • Load your AsyncApi Schema from local file or any URL
  • Supports AsyncApi in JSON and YAML format
  • Supports all versions of AsyncAPI
  • more coming . . .

How it works

asyncapi-validator validates the payload of the messages of a certian message, as described in your schema document. To validate aginst a certian message, it needs to find the messsage are you pointing to in schema document. For that, you need to pass it channle, operation, and key of the message.

validate(key, payload, channel, operation)
  • One channel should be defined only once in your whole schema document.
  • The key should be unique for an operation on a channel.

That means,

  • Messages going to different operations on one channel, can have same key.
  • Messages going to different channels, can have same key

Methods

.fromSource()

/** 
 * Load and Parse the schema from source. You only need to do this once, and then just use .validate() method for validations.
 * @param {string} path - local path or URL of schema
 * @param {Object} options - options for validation
 * @returns {Promise}
 */
fromSource(path, options)

Options

valuetypedescription
ignoreArraybooleanoptionalIf true, then if schema is defined as an array and payload is an object, then payload will be placed inside an array before validation.
msgIdentifierstringrequired with AsyncAPI v2Name of 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

.validate()

/**
 * 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 (optional with AsyncAPI v1)
 * @param {string} operation - required - publish | subscribe (optional with AsyncAPI v1)
 * @returns {boolean}
 */
validate(key, payload, channel, operation)

Note: 'channel' and 'operation' can only be used with AsyncAPI v2. Both are required with AsyncAPI v2.

Example usage,

Example 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: 'alex@mail.com',
}, 'user-events', 'publish')

In above example, "msgIdentifier" is "x-custom-key". That's why, "UserDeleted" has been use as "key" in "va.validate()"

Example usage with AsyncAPI V1 (deprecated)

const AsyncApiValidator = require('asyncapi-validator')
let va = await AsyncApiValidator.fromSource('./api.yaml')

// validate 'UserDeleted' key with payload
va.validate('UserDeleted', {
  userId: 'bd58d14f-fd3e-449c-b60c-a56548190d68',
  deletedBy: 'bd58d14f-fd3e-449c-b60c-a56548190d68',
  deletedAt: '2017-01-09T08:27:22.222Z',
})

// validate 'UserCreated' key with payload
va.validate('UserCreated', {1:1})

For these examples to work, key UserDeleted and UserCreated must be present in such way.

components:
  messages:
    UserDeleted:
              ...
              ...
    UserCreated:
              ...
              ...

Errors

Error thrown from asyncapi-validator will have these properties.

keytypevaluedescription
namestringAsyncAPIValidationErrorAsyncAPIValidationError
keystring"key" of payload against which schema is validated
messagestringerrorsText from AJV
errorsarrayArray of errors from AJV

Error Example

{
  AsyncAPIValidationError: data.type should 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: 'should be equal to one of the allowed values'
      }
    ]
}
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free