npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

asyncapi-validator

v4.0.0

Published

message validator through asyncapi schema

Downloads

46,979

Readme

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: UserDeletedMessage
        payload:
          type: object
          properties:
            userEmail:
              type: string
            userId:
              type: string
const AsyncApiValidator = require('asyncapi-validator')
let va = await AsyncApiValidator.fromSource('./api.yaml')

// validate messageId 'UserDeleted'
va.validate('UserDeleted', {
  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'
      }
    ]
}