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

feat: integrate asyncapi-validator to validate incomming messages #53

Merged
merged 11 commits into from
Mar 30, 2021
18 changes: 7 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
- [How to use the template](#how-to-use-the-template)
* [CLI](#cli)
- [Template configuration](#template-configuration)
- [Custom hooks that you can disable](#custom-hooks-that-you-can-disable)
- [Development](#development)
- [Contributors](#contributors)

Expand Down Expand Up @@ -86,10 +85,14 @@ npm start
#for testing your server you can use mqtt client. open a new terminal and install it using:
npm install mqtt -g

#publish your message.
mqtt pub -t 'smartylighting/streetlights/1/0/event/{streetlightId}/lighting/measured' -h 'test.mosquitto.org' -m '{"id": 1, "lumens": 3, "sentAt": "2017-06-07T12:34:32.000Z"}'
#publish an invalid message.
mqtt pub -t 'smartylighting/streetlights/1/0/event/123/lighting/measured' -h 'test.mosquitto.org' -m '{"id": 1, "lumens": "3", "sentAt": "2017-06-07T12:34:32.000Z"}'

# You should see the sent message in the logs of the previously started server.
#publish a valid message
mqtt pub -t 'smartylighting/streetlights/1/0/event/123/lighting/measured' -h 'test.mosquitto.org' -m '{"id": 1, "lumens": 3, "sentAt": "2017-06-07T12:34:32.000Z"}'

#You should see the sent message in the logs of the previously started server.
#Notice that the server automatically validates incoming messages and logs out validation errors
```


Expand All @@ -102,13 +105,6 @@ You can configure this template by passing different parameters in the Generator
|---|---|---|---|
|server|The server you want to use in the code.|Yes|`production`|

## Custom hooks that you can disable

The functionality of this template is extended with different hooks that you can disable like this in the Generator CLI: `-d HOOK_TYPE=HOOK_NAME`

Type | Name | Description
---|---|---
generate:after | createAsyncapiFile | It creates AsyncAPI file with content of the spec file passed to the generator

## Development

Expand Down
1 change: 1 addition & 0 deletions template/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"dotenv": "^8.1.0",
"hermesjs": "2.x",
"hermesjs-router": "1.x",
"asyncapi-validator": "^3.0.0",
{% if asyncapi.server(params.server).protocol() === 'mqtt' -%}
"hermesjs-mqtt": "2.x",
{%- endif -%}
Expand Down
9 changes: 7 additions & 2 deletions template/src/api/middlewares/error-logger.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
const { red, gray } = require('colors/safe');

module.exports = (err, message, next) => {
console.error(red(`❗ ${err.message}`));
if (err.stack) console.error(gray(err.stack.substr(err.stack.indexOf('\n')+1)));
if (err.name === 'AsyncAPIValidationError'){
console.error(red(`❗ Message Rejected. ${err.message}`));
}
else {
console.error(red(`❗ ${err.message}`));
if (err.stack) console.error(gray(err.stack.substr(err.stack.indexOf('\n')+1)));
}
next();
};
3 changes: 3 additions & 0 deletions template/src/api/routes/$$channel$$.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Router = require('hermesjs/lib/router');
const {validateMessage} = require('../../lib/message-validator');
const router = new Router();
const {{ channelName | camelCase }}Handler = require('../handlers/{{ channelName | convertToFilename }}');
module.exports = router;
Expand All @@ -10,6 +11,7 @@ module.exports = router;
{%- endif %}
router.use('{{ channelName | toHermesTopic }}', async (message, next) => {
try {
await validateMessage(message.payload,'{{ channelName }}','{{ channel.publish().message().name() }}','publish');
await {{ channelName | camelCase }}Handler.{{ channel.publish().id() }}({message});
next();
} catch (e) {
Expand All @@ -26,6 +28,7 @@ router.use('{{ channelName | toHermesTopic }}', async (message, next) => {
{%- endif %}
router.useOutbound('{{ channelName | toHermesTopic }}', async (message, next) => {
try {
await validateMessage(message.payload,'{{ channelName }}','{{ channel.subscribe().message().name() }}','subscribe');
await {{ channelName | camelCase }}Handler.{{ channel.subscribe().id() }}({message});
next();
} catch (e) {
Expand Down
6 changes: 6 additions & 0 deletions template/src/lib/message-validator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const AsyncApiValidator = require('asyncapi-validator');

module.exports.validateMessage = async (payload, channel,name,operation)=> {
let va = await AsyncApiValidator.fromSource('./asyncapi.yaml', {msgIdentifier: 'name'});
KhudaDad414 marked this conversation as resolved.
Show resolved Hide resolved
va.validate(name, payload, channel, operation);
}