Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update for asyncapi schema v3 #65

Merged
merged 6 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/workflows/test-coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ jobs:
npm run lint
npm test

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
- name: Upload coverage reports to Codecov with GitHub Action
uses: codecov/[email protected]
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
Change Log
==========

Version 5.0.0 *(2024-07-21)*
----------------------------
### Breaking:
* Errors messages format for initial check on AsyncApi document has been updated.
* _Note: No change in errors thrown from `validate()` method._
* Deprecate `validateByMessageId()` method as `messageId` was removed in AsyncApi v3.0.0. More details here [asyncapi/spec/issues/978](https://github.com/asyncapi/spec/issues/978)

### New / Improvements:
* Support AsyncAPI schema v3.0.0
* Start using @asyncapi/parser v3

Version 4.0.0 *(2022-05-22)*
----------------------------
### Breaking:
Expand Down
115 changes: 63 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
![Unit Tests](https://github.com/WaleedAshraf/asyncapi-validator/workflows/Unit%20Tests/badge.svg?branch=master) [![codecov](https://codecov.io/gh/WaleedAshraf/asyncapi-validator/branch/master/graph/badge.svg)](https://codecov.io/gh/WaleedAshraf/asyncapi-validator) ![CodeQL](https://github.com/WaleedAshraf/asyncapi-validator/workflows/CodeQL/badge.svg?branch=master)
![Unit Tests](https://github.com/WaleedAshraf/asyncapi-validator/workflows/Unit%20Tests/badge.svg) [![codecov](https://codecov.io/gh/WaleedAshraf/asyncapi-validator/graph/badge.svg?token=QlYEl26MvM)](https://codecov.io/gh/WaleedAshraf/asyncapi-validator) ![CodeQL](https://github.com/WaleedAshraf/asyncapi-validator/workflows/CodeQL/badge.svg)

# asyncapi-validator

Message validator through AsyncAPI schema
Validate messages through AsyncApi

_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.
_Note: This package only support AsyncApi Schema v2.0.0 and above._

`npm i asyncapi-validator`

Expand All @@ -13,18 +13,18 @@ _Note: This package only support AsyncAPI Schema v2.0.0 and above. Since v3.0.0,
- 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
- Supports AsyncApi v2.0.0 and above

## Content
- [Class Methods](#class-methods)
- [AsyncApiValidator.fromSource()](#asyncapivalidatorfromsource)
- [Options](#options)
- [Instance Methods / Properties](#instance-methods--properties)
- [.validateByMessageId()](#validateByMessageId)
- [.validate()](#validate)
- [.validateByMessageId()](#validateByMessageId) - _deprecated_
- [.schema](#schema)
- [Example usage with .validateByMessageId() method](#example-usage-with-validatebymessageid-method)
- [Example usage with .validate() method](#example-usage-with-validate-method)
- [Example usage with .validateByMessageId() method](#example-usage-with-validatebymessageid-method)
- [Errors](#errors)
- [Error Example](#error-example)

Expand All @@ -44,83 +44,96 @@ AsyncApiValidator.fromSource(source, options)
#### Options
| value | type | | description |
|-----|----|----|---|
| msgIdentifier | string | required | Name of the parameter whose value will be used as `"key"` in `.validate()` method. Recommendation is to use `"name"` as described in [message-object](https://www.asyncapi.com/docs/reference/specification/v3.0.0#messageObject). You can also use [Specification Extensions](https://www.asyncapi.com/docs/reference/specification/v3.0.0#specificationExtensions). |
| 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](https://asyncapi.io/docs/specifications/2.0.0/#a-name-messageobject-a-message-object). You can also use [Specification Extensions](https://asyncapi.io/docs/specifications/2.0.0/#specificationExtensions). |
| 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](https://github.com/asyncapi/parser-js/blob/master/lib/parser.js#L41) |
| path | string | optional | Path to the AsyncApi document. |

## Instance Methods / Properties
## Instance Methods and Properties

### .validateByMessageId()
### .validate()

Here `messageId` should be as [defined in AsyncAPI Schema v2.4.0](https://www.asyncapi.com/docs/specifications/v2.4.0#messageObject). To use this method, your AsyncAPI Schema version should be >= v2.4.0.
You should provide `msgIdentifier` in AsyncApiValidator `options`.

```js
/**
* Method to validate the Payload against schema definition.
* @param {string} key - required - messageId
* @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}
*/
.validateByMessageId(key, payload)
.validate(key, payload, channel, operation)
```

### .validate()
### .validateByMessageId() - deprecated
_This method is deprecated as `messageId` was removed in AsyncApi v3.0.0. More details here [asyncapi/spec/issues/978](https://github.com/asyncapi/spec/issues/978) ._

To use this method for validation, you should provide `msgIdentifier` in AsyncApiValidator `options`.
Here `messageId` should be as [defined in AsyncApi Schema v2.4.0](https://www.asyncapi.com/docs/specifications/v2.4.0#messageObject). To use this method, your AsyncApi Schema version should be >= v2.4.0 and <3.0.0.

```js
/**
* Method to validate the Payload against schema definition.
* @param {string} key - required - message key
* @param {string} key - required - messageId
* @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)
.validateByMessageId(key, payload)
```

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

## Example usage with .validateByMessageId() method
## Example usage with .validate() method
Schema
```yaml
asyncapi: 2.4.0

asyncapi: 3.0.0
info:
title: User Events
title: Streetlights Kafka API
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
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.
```
```js
const AsyncApiValidator = require('asyncapi-validator')
let va = await AsyncApiValidator.fromSource('./api.yaml')
let va = await AsyncApiValidator.fromSource('./api.yaml', {msgIdentifier: 'x-unique-id'})

// validate messageId 'UserRemoved'
va.validateByMessageId('UserRemoved', {
userId: '123456789',
userEmail: '[email protected]',
})
// 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 .validate() method
## Example usage with .validateByMessageId() method
Schema
```yaml
asyncapi: 2.0.0
asyncapi: 2.4.0

info:
title: User Events
Expand All @@ -131,8 +144,7 @@ channels:
description: user related events
publish:
message:
name: UserDeletedMessage
x-custom-key: UserDeleted
messageId: UserRemoved
payload:
type: object
properties:
Expand All @@ -143,15 +155,14 @@ channels:
```
```js
const AsyncApiValidator = require('asyncapi-validator')
let va = await AsyncApiValidator.fromSource('./api.yaml', {msgIdentifier: 'x-custom-key'})
let va = await AsyncApiValidator.fromSource('./api.yaml')

// validate 'UserDeleted' on channel 'user-events' with operation 'publish'
va.validate('UserDeleted', {
// validate messageId 'UserRemoved'
va.validateByMessageId('UserRemoved', {
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.
Expand Down
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ declare module 'asyncapi-validator' {
key: string,
payload: unknown,
channel: string,
operation: 'publish' | 'subscribe',
operation: 'publish' | 'subscribe' | 'send' | 'receive',
) => boolean;

validateByMessageId: (
Expand Down
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ module.exports = {
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
testRegex: ['./test/src/*', './test/v2.*/*'],
testRegex: ['./test/src/*', './test/v2.*/*', './test/v3.*/*'],

// This option allows the use of a custom results processor
// testResultsProcessor: null,
Expand Down
Loading
Loading