Skip to content

Commit

Permalink
fix: let validation throw an exception when payload is invalid (#179)
Browse files Browse the repository at this point in the history
Co-authored-by: Lukasz Gornicki <[email protected]>
  • Loading branch information
smoya and derberg authored Nov 14, 2022
1 parent 799cbed commit 13021ca
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
4 changes: 3 additions & 1 deletion template/src/api/routes/$$channel$$.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ router.use('{{ channelName | toHermesTopic }}', async (message, next) => {
// For oneOf, only one message schema should match.
// Validate payload against each message and count those which validate
{% for i in range(0, channel.publish().messages().length) -%}
nValidated = await validateMessage(message.payload,'{{ channelName }}','{{ channel.publish().message(i).name() }}','publish', nValidated);
try {
nValidated = await validateMessage(message.payload,'{{ channelName }}','{{ channel.publish().message(i).name() }}','publish', nValidated);
} catch { };
{% endfor -%}
if (nValidated === 1) {
await {{ channelName | camelCase }}Handler.{{ channel.publish().id() }}({message});
Expand Down
11 changes: 4 additions & 7 deletions template/src/lib/message-validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ const AsyncApiValidator = require('asyncapi-validator');

// Try to parse the payload, and increment nValidated if parsing was successful.
module.exports.validateMessage = async (payload, channelName, messageName, operation, nValidated=0) => {
try {
const va = await AsyncApiValidator.fromSource('./asyncapi.yaml', {msgIdentifier: 'name'});
va.validate(messageName, payload, channelName, operation);
nValidated++;
} catch (e) {
return nValidated;
}
const va = await AsyncApiValidator.fromSource('./asyncapi.yaml', {msgIdentifier: 'name'});
va.validate(messageName, payload, channelName, operation);
nValidated++;

return nValidated;
};

0 comments on commit 13021ca

Please sign in to comment.