Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

asyncapi-validator

Package Overview
Dependencies
Maintainers
1
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

asyncapi-validator

message validator through asyncapi schema

  • 5.0.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
9.1K
decreased by-4.44%
Maintainers
1
Weekly downloads
 
Created
Source

Unit Tests codecov CodeQL

asyncapi-validator

Validate messages through AsyncApi

Note: This package only support AsyncApi Schema v2.0.0 and above.

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
valuetypedescription
msgIdentifierstringrequiredName 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.
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.
pathstringoptionalPath to the AsyncApi document.

Instance Methods and Properties

.validate()

You should provide msgIdentifier in AsyncApiValidator options.

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

.validateByMessageId() - deprecated

This method is deprecated as messageId was removed in AsyncApi v3.0.0. More details here asyncapi/spec/issues/978 .

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 and <3.0.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)

.schema

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

Example usage with .validate() method

Schema

asyncapi: 3.0.0
info:
  title: Streetlights Kafka API
  version: 1.0.0
channels:
  lightingMeasured:
    messages:
      lightMeasured:
        $ref: '#/components/messages/lightMeasured'
operations:
  sendLightMeasurement:
    action: send
    channel:
      $ref: '#/channels/lightingMeasured'
    messages:
      - $ref: '#/channels/lightingMeasured/messages/lightMeasured'
components:
  messages:
    lightMeasured:
      x-unique-id: lightMeasured
      payload:
        $ref: '#/components/schemas/lightMeasuredPayload'
  schemas:
    lightMeasuredPayload:
      type: object
      properties:
        lumens:
          type: integer
          minimum: 0
          description: Light intensity measured in lumens.
const AsyncApiValidator = require('asyncapi-validator')
let va = await AsyncApiValidator.fromSource('./api.yaml', {msgIdentifier: 'x-unique-id'})

// validate 'lightMeasured' on channel 'lightingMeasured' with operation 'send'
va.validate('lightMeasured', {
  lumens: 0,
  sentAt: '2019-08-24T14:15:22Z'
}, 'lightingMeasured', 'send')

In above example, "msgIdentifier" is "'x-unique-id". That is why, "lightMeasured" is used as "key" in "va.validate()" method.

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

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 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'
      }
    ]
}

Keywords

FAQs

Package last updated on 22 Aug 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc