Skip to content

Commit

Permalink
docs: add documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Dieter Stinglhamber committed Jan 4, 2024
1 parent 1d8b4a0 commit 34ab9a7
Show file tree
Hide file tree
Showing 4 changed files with 251 additions and 145 deletions.
214 changes: 146 additions & 68 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@

Message validation package for YAML and JSON AsyncAPI documents.

This package is compatible with AsyncAPI documents v2.x.x and v3.0.0.
This package:

- Load and parse your AsyncAPI documents from a file, an url or an in-line schema
- Support AsyncAPI documents v2.x.x and v3.x.x
- Support both YAML and JSON documents

## Installation

Expand All @@ -21,92 +25,166 @@ pnpm install asyncapi-validation

## Usage

### Using a remote schema
### Parsing Functions

<dl>
<dt><a href="#fromFile">fromFile(path)</a> ⇒ <code>Promise.&lt;ValidationFunction&gt;</code></dt>
<dd><p>Parses an AsyncAPI schema from a file and returns a validation function.</p>
</dd>
<dt><a href="#fromUrl">fromUrl(url)</a> ⇒ <code>Promise.&lt;ValidationFunction&gt;</code></dt>
<dd><p>Parses an AsyncAPI schema from a URL and returns a validation function.</p>
</dd>
<dt><a href="#fromSchema">fromSchema(schema)</a> ⇒ <code>Promise.&lt;ValidationFunction&gt;</code></dt>
<dd><p>Parses an AsyncAPI schema from a string and returns a validation function.</p>
</dd>
</dl>

<a name="fromFile"></a>

#### fromFile(path) ⇒ <code>Promise.&lt;ValidationFunction&gt;</code>

Parses an AsyncAPI schema from a file and returns a validation function.

**Kind**: global function
**Returns**: <code>Promise.&lt;ValidationFunction&gt;</code> - A promise that resolves to the validation function.
**Throws**:

- <code>AsyncAPIParsingError</code> if the schema is not valid or has governance issues.

| Param | Type | Description |
| ----- | ------------------- | ------------------------------------- |
| path | <code>string</code> | The path to the AsyncAPI schema file. |

**Example**

```js
const validator = await asyncApiValidation.parseFromFile('path/to/schema.yaml');
validator('messageKey', { foo: 'bar' });
```

<a name="fromUrl"></a>

#### fromUrl(url) ⇒ <code>Promise.&lt;ValidationFunction&gt;</code>

Parses an AsyncAPI schema from a URL and returns a validation function.

**Kind**: global function
**Returns**: <code>Promise.&lt;ValidationFunction&gt;</code> - A promise that resolves to the validation function.
**Throws**:

- <code>AsyncAPIParsingError</code> if the schema is not valid or has governance issues.

| Param | Type | Description |
| ----- | ------------------- | ------------------------------- |
| url | <code>string</code> | The URL of the AsyncAPI schema. |

```ts
import asyncAPIValidation from 'asyncapi-validation';
**Example**

const validator = await asyncAPIValidation.fromUrl(
```js
const validator = await asyncApiValidation.fromUrl(
'https://example.org/schema.yaml'
);
validator('messageName', { foo: 'bar' });
validator('messageId', { foo: 'bar' });
validator('messageKey', { foo: 'bar' });
```

# Using a local schema
<a name="fromSchema"></a>

```ts
const validator = await asyncAPIValidation.fromUrl('./schema.yaml');
validator('messageName', { foo: 'bar' });
validator('messageId', { foo: 'bar' });
```
#### fromSchema(schema) ⇒ <code>Promise.&lt;ValidationFunction&gt;</code>

# Using an in-line schema

```ts
const validator = await asyncAPIValidation.fromSchema(`asyncapi: 3.0.0
info:
title: Account Service
version: 1.0.0
description: This service is in charge of processing user signups
channels:
userSignedup:
address: user/signedup
messages:
UserSignedUp:
$ref: '#/components/messages/UserSignedUp'
operations:
sendUserSignedup:
action: send
channel:
$ref: '#/channels/userSignedup'
messages:
- $ref: '#/channels/userSignedup/messages/UserSignedUp'
components:
messages:
UserSignedUp:
payload:
type: object
properties:
displayName:
type: string
description: Name of the user
email:
type: string
format: email
description: Email of the user
`);
validator('messageName', { foo: 'bar' });
validator('messageId', { foo: 'bar' });
```
Parses an AsyncAPI schema from a string and returns a validation function.

## Contributing
**Kind**: global function
**Returns**: <code>Promise.&lt;ValidationFunction&gt;</code> - A promise that resolves to the validation function.
**Throws**:

### Tests
- <code>AsyncAPIParsingError</code> if the schema is not valid or has governance issues.

The test suite can be run using pnpm scripts:
| Param | Type | Description |
| ------ | ------------------- | -------------------------------- |
| schema | <code>string</code> | The AsyncAPI schema as a string. |

```bash
pnpm test
**Example**

```js
const validator = await asyncApiValidation.fromSchema('asyncapi: 2.0.0');
validator('messageKey', { foo: 'bar' });
```

Tests can be found in the (tests)[./tests] folder.
### Validator Function

### Linting
<a name="validate"></a>

The following pnpm script can be used to find out about the possible linting errors:
#### validate(schema) ⇒ <code>ValidationFunction</code>

```bash
pnpm lint
Validates the provided AsyncAPI schema and returns a validation function.

**Kind**: global function
**Returns**: <code>ValidationFunction</code> - The validation function.

| Param | Type | Description |
| ------ | ------------------------ | --------------------------- |
| schema | <code>ParseOutput</code> | The parsed AsyncAPI schema. |

<a name="validate..validatorFunction"></a>

##### validate~validatorFunction(key, payload) ⇒ <code>boolean</code>

Validates the provided payload against the AsyncAPI schema.

**Kind**: inner method of [<code>validate</code>](#validate)
**Returns**: <code>boolean</code> - true if the payload is valid.
**Throws**:

- <code>Error</code> if no messages are found for the given key.
- <code>AsyncAPIValidationError</code> if the payload fails validation.

| Param | Type | Description |
| ------- | -------------------- | ----------------------------------- |
| key | <code>string</code> | The key of the message to validate. |
| payload | <code>unknown</code> | The payload to validate. |

**Example**

```js
const validator = await asyncApiValidation.fromSchema('asyncapi: 2.0.0');
validator('messageKey', { foo: 'bar' });
```

### Linting error prevention
### Errors

<a name="AsyncAPIParsingError"></a>

#### AsyncAPIParsingError

Represents an error that occurs during the parsing of an AsyncAPI document.

**Kind**: global class
<a name="new_AsyncAPIParsingError_new"></a>

##### new AsyncAPIParsingError(message, [errors])

Represents an error that occurs during the parsing of an AsyncAPI document.

| Param | Type | Description |
| -------- | ------------------------------------- | ---------------------------------------------------------------------- |
| message | <code>string</code> | The error message. |
| [errors] | <code>Array.&lt;Diagnostic&gt;</code> | Optional array of diagnostic errors associated with the parsing error. |

<a name="AsyncAPIValidationError"></a>

#### AsyncAPIValidationError

Represents an error that occurs during AsyncAPI validation.

**Kind**: global class
<a name="new_AsyncAPIValidationError_new"></a>

[Husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged) are set up to check staged files for linting issues. When new changes are commited all the updated files will be checked. If the linting fails for one of them the operation will be cancelled.
##### new AsyncAPIValidationError(message, key, [errors])

## Built with
Represents an error that occurs during AsyncAPI validation.

- [NodeJs](https://nodejs.org/)
- [TypeScript](https://www.typescriptlang.org/)
- [AsyncAPI parser](https://www.asyncapi.com/tools/parsers)
- [Ajv js](https://ajv.js.org/)
| Param | Type | Description |
| -------- | ----------------------------------------------------------- | -------------------------------------- |
| message | <code>string</code> | The error message. |
| key | <code>string</code> | The key associated with the error. |
| [errors] | <code>Array.&lt;ErrorObject&gt;</code> \| <code>null</code> | The array of validation error objects. |
10 changes: 10 additions & 0 deletions src/AsyncAPIParsingError.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { type Diagnostic } from '@asyncapi/parser';

/**
* Represents an error that occurs during the parsing of an AsyncAPI document.
* @class
*/
export default class AsyncAPIParsingError extends Error {
protected errors?: Diagnostic[];

/**
* Represents an error that occurs during the parsing of an AsyncAPI document.
*
* @param {string} message - The error message.
* @param {Diagnostic[]} [errors] - Optional array of diagnostic errors associated with the parsing error.
*/
constructor(message: string, errors?: Diagnostic[]) {
super(message, { cause: errors });

Expand Down
11 changes: 11 additions & 0 deletions src/AsyncAPIValidationError.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import { type ErrorObject } from 'ajv';

/**
* Represents an error that occurs during AsyncAPI validation.
* @class
*/
export default class AsyncAPIValidationError extends Error {
protected key: string;

protected errors?: ErrorObject[] | null;

/**
* Represents an error that occurs during AsyncAPI validation.
*
* @param {string} message - The error message.
* @param {string} key - The key associated with the error.
* @param {ErrorObject[]|null} [errors] - The array of validation error objects.
*/
constructor(message: string, key: string, errors?: ErrorObject[] | null) {
super(message);

Expand Down
Loading

0 comments on commit 34ab9a7

Please sign in to comment.