From 8877f896604ceac04d0716231be9dedec0ddd08f Mon Sep 17 00:00:00 2001 From: Bishal Date: Thu, 20 Jun 2024 21:58:01 +0000 Subject: [PATCH] log the name of the message --- package.json | 1 + template/src/lib/message-validator.js | 48 ++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 65955b7f..0c52f5ab 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "eslint-plugin-react": "^7.34.1", "filenamify": "^4.3.0", "js-beautify": "^1.15.1", + "js-yaml": "^4.1.0", "lodash": "^4.17.21", "markdown-toc": "^1.2.0" }, diff --git a/template/src/lib/message-validator.js b/template/src/lib/message-validator.js index 17a9f049..828b6be9 100644 --- a/template/src/lib/message-validator.js +++ b/template/src/lib/message-validator.js @@ -1,6 +1,33 @@ +const yaml = require('js-yaml'); +const fs = require('fs'); const path = require('path'); const AsyncApiValidator = require('asyncapi-validator'); +function validateMessageIdentifiers(asyncApiSpec) { + const messages = asyncApiSpec.components.messages; + const missingNames = []; + + for (const [messageName, messageObj] of Object.entries(messages)) { + if (!messageObj.name) { + missingNames.push(messageName); + } + } + + return missingNames; +} + +function performPreGenValidation(asyncApiFilePath) { + const fileContents = fs.readFileSync(asyncApiFilePath, 'utf8'); + const asyncApiSpec = yaml.load(fileContents); + + const missingNames = validateMessageIdentifiers(asyncApiSpec); + + if (missingNames.length > 0) { + const errorMessage = `msgIdentifier "name" does not exist for message(s): ${missingNames.join(', ')}`; + throw new Error(errorMessage); + } +} + // Try to parse the payload, and increment nValidated if parsing was successful. module.exports.validateMessage = async ( payload, @@ -9,12 +36,17 @@ module.exports.validateMessage = async ( operation, nValidated = 0 ) => { - const asyncApiFilePath = path.resolve(__dirname, '../../asyncapi.yaml'); - const va = await AsyncApiValidator.fromSource(asyncApiFilePath, { - msgIdentifier: 'name', - }); - va.validate(messageName, payload, channelName, operation); - nValidated++; - - return nValidated; + try { + const asyncApiFilePath = path.resolve(__dirname, "../../asyncapi.yaml"); + const va = await AsyncApiValidator.fromSource(asyncApiFilePath, { + msgIdentifier: "name", + }); + va.validate(messageName, payload, channelName, operation); + nValidated++; + + return nValidated; + } catch (error) { + error.name = "AsyncAPIValidationError"; + throw error; + } };