diff --git a/src/app.js b/src/app.js index 92ed138..e6d8e62 100644 --- a/src/app.js +++ b/src/app.js @@ -1,74 +1,62 @@ -'use strict'; -require('module-alias/register'); -const express = require('express'); -const cors = require('cors'); -require('dotenv').config({ path: './.env' }); -const path = require('path'); -const packageInstaller = require('./utils/packageInstaller'); -const executeScripts = require('./scripts'); - - - -(async () => { - try { - - - // First, install necessary packages - await packageInstaller(process.env.REQUIRED_PACKAGES); - - // Next, execute fetchRouteConfigs and combineRoutesConfigs - await executeScripts(); - - const dependencyManager = require('@helpers/dependencyManager') - await dependencyManager() - - // After scripts execution, continue with environment data validation - let environmentData = require('./envVariables')(); - if (!environmentData.success) { - console.error('Server could not start. Not all environment variables are provided'); - process.exit(1); - } - - // Initialize the rest of the application (after the scripts are done) - require('./init'); - - // Create an Express app instance - const app = express(); - app.set('trust proxy', parseInt(process.env.RATE_LIMITER_NUMBER_OF_PROXIES)); - - // Middleware and CORS setup - app.use(cors()); - - // Set Access-Control-Allow-Origin header - app.use((req, res, next) => { - res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_HOST); - next(); - }); - - // Load router packages and initialize the router - const routerPackages = require('@utils/packageLoader').packageLoader(); - const validatedPackages = routerPackages; // Bypassing the validator for now - const { initializeRouter } = require('@router'); - app.use(initializeRouter(validatedPackages)); - - // Serve API documentation - app.get(process.env.API_DOC_URL, (req, res) => { - res.sendFile(path.join(__dirname, './api-doc/index.html')); - }); - - // Start the server - app.listen(process.env.APPLICATION_PORT, (err) => { - if (err) { - onError(err); - } - console.log('Environment: ' + process.env.APPLICATION_ENV); - console.log('Application is running on port: ' + process.env.APPLICATION_PORT); - - }); - - } catch (error) { - // Handle any error from script execution or package installation - console.error('Error in app initialization:', error); - process.exit(1); - } -})(); +'use strict' +require('module-alias/register') +const express = require('express') +const cors = require('cors') +require('dotenv').config({ path: './.env' }) +const path = require('path') +const packageInstaller = require('./utils/packageInstaller') +const executeScripts = require('./scripts') + +;(async () => { + try { + // First, install necessary packages + await packageInstaller(process.env.REQUIRED_PACKAGES) + + // Next, execute fetchRouteConfigs and combineRoutesConfigs + await executeScripts() + + const dependencyManager = require('@helpers/dependencyManager') + await dependencyManager() + + // After scripts execution, continue with environment data validation + let environmentData = require('./envVariables')() + if (!environmentData.success) { + console.error('Server could not start. Not all environment variables are provided') + process.exit(1) + } + // Initialize the rest of the application (after the scripts are done) + require('./init') + + // Create an Express app instance + const app = express() + app.set('trust proxy', parseInt(process.env.RATE_LIMITER_NUMBER_OF_PROXIES)) + + // Middleware and CORS setup + app.use(cors()) + + // Set Access-Control-Allow-Origin header + app.use((req, res, next) => { + res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_HOST) + next() + }) + // Load router packages and initialize the router + const routerPackages = require('@utils/packageLoader').packageLoader() + const validatedPackages = routerPackages // Bypassing the validator for now + const { initializeRouter } = require('@router') + app.use(initializeRouter(validatedPackages)) + // Serve API documentation + app.get(process.env.API_DOC_URL, (req, res) => { + res.sendFile(path.join(__dirname, './api-doc/index.html')) + }) + // Start the server + app.listen(process.env.APPLICATION_PORT, (err) => { + if (err) { + onError(err) + } + }) + } catch (error) { + // Handle any error from script execution or package installation + console.error('Error in app initialization:', error) + process.exit(1) + } +})() diff --git a/src/configs/dependencyConfig.json b/src/configs/dependencyConfig.json index b1a6030..3c7943f 100644 --- a/src/configs/dependencyConfig.json +++ b/src/configs/dependencyConfig.json @@ -1,9 +1,4 @@ { "requiredDependencies": [], - "supportedDependencies": [ - { - "name": "kafka", - "packageName": "elevate-kafka" - } - ] + "supportedDependencies": [] } diff --git a/src/configs/routesConfigs.js b/src/configs/routesConfigs.js index bb81181..2c937ab 100644 --- a/src/configs/routesConfigs.js +++ b/src/configs/routesConfigs.js @@ -2,6 +2,6 @@ const config = require('@configs/.config.json') exports.routesConfigs = { - services: process.env.REQUIRED_BASE_PACKAGES.split(","), + services: process.env.REQUIRED_BASE_PACKAGES, routes: config.routes, } diff --git a/src/configs/routesConfigs/shiksha-user.json b/src/configs/routesConfigs/shiksha-user.json new file mode 100644 index 0000000..59ac9b2 --- /dev/null +++ b/src/configs/routesConfigs/shiksha-user.json @@ -0,0 +1,30 @@ +{ + "routes": [ + { + "sourceRoute": "/interface/v1/account/create", + "type": "POST", + "priority": "MUST_HAVE", + "inSequence": false, + "orchestrated": false, + "targetPackages": [ + { + "basePackageName": "user", + "packageName": "shiksha-user" + } + ] + }, + { + "sourceRoute": "/interface/v1/account/login", + "type": "POST", + "priority": "MUST_HAVE", + "inSequence": false, + "orchestrated": false, + "targetPackages": [ + { + "basePackageName": "user", + "packageName": "shiksha-user" + } + ] + } + ] +} \ No newline at end of file diff --git a/src/generics/request.js b/src/generics/request.js index 5620609..2aed4f2 100644 --- a/src/generics/request.js +++ b/src/generics/request.js @@ -1,4 +1,4 @@ -const request = require('request'); +const request = require('request') /** * Makes a GET request to the specified URL with optional token headers. @@ -8,50 +8,51 @@ const request = require('request'); * @returns {Promise} - A promise that resolves to the fetched result object. */ var get = function (url, token = '', internal_access_token = '') { - return new Promise((resolve, reject) => { - try { - let headers = { - 'content-type': 'application/json', - }; - if (internal_access_token) { - headers['internal_access_token'] = internal_access_token; - } + return new Promise((resolve, reject) => { + try { + let headers = { + 'content-type': 'application/json', + } + if (internal_access_token) { + headers['internal_access_token'] = internal_access_token + } - if (token) { - headers['x-auth-token'] = token; - } + if (token) { + headers['x-auth-token'] = token + } - const options = { - headers: headers, - }; + const options = { + headers: headers, + } - request.get(url, options, (err, response) => { - let result = { - success: true, - }; + request.get(url, options, (err, response) => { + console.log('url: ', url) + //console.log('options: ', options) + let result = { + success: true, + } + if (err) { + result.success = false + result.error = err + } else { + let body = response.body + try { + result.data = typeof body === 'string' ? JSON.parse(body) : body // Attempt to parse the JSON string JSON.parse(body); + } catch (jsonError) { + console.log('Error parsing JSON : ', jsonError) + result.success = false + result.error = 'Error parsing JSON' + } + } - if (err) { - result.success = false; - result.error = err; - } else { - let body = response.body; - try { - result.data = typeof body === "string" ? JSON.parse(body) : body ; // Attempt to parse the JSON string JSON.parse(body); - } catch (jsonError) { - console.log('Error parsing JSON : ',jsonError) - result.success = false; - result.error = 'Error parsing JSON'; - } - } - - return resolve(result); - }); - } catch (error) { - return reject(error); - } - }); -}; + return resolve(result) + }) + } catch (error) { + return reject(error) + } + }) +} module.exports = { - get + get, } diff --git a/src/helpers/dependencyManager.js b/src/helpers/dependencyManager.js index e69490b..5ea63d7 100644 --- a/src/helpers/dependencyManager.js +++ b/src/helpers/dependencyManager.js @@ -3,68 +3,53 @@ const dependencyConfigs = require('@configs/dependencyConfig.json') const requiredEnvsJSON = require('../configs/requiredEnvs.json') -const packageLoader = require('@utils/packageLoader'); +const packageLoader = require('@utils/packageLoader') const dependencyManager = () => { try { const { supportedDependencies } = dependencyConfigs const supportedDependencyMap = new Map() - supportedDependencies.map((dependency) => { const dependencyPackage = require(dependency.packageName) supportedDependencyMap.set(dependency.name, dependencyPackage) return dependency.name }) - const packages = packageLoader.packageLoader() - - packages.forEach(packageInfo => { - - const { packageName } = packageInfo.packageMeta; - - - - + packages.forEach((packageInfo) => { + const { packageName } = packageInfo.packageMeta const { dependencyManager, requiredEnvs } = require(packageName) - requiredEnvsJSON.requiredEnvs = { ...requiredEnvsJSON.requiredEnvs, ...requiredEnvs, } - - if(packageInfo.requiredDependencies){ - let requiredDependencies = packageInfo.requiredDependencies(); - - if( requiredDependencies.length > 0) { - + if (packageInfo.requiredDependencies) { + let requiredDependencies = packageInfo.requiredDependencies() + if (requiredDependencies.length > 0) { const injectionPackageMap = new Map() const unsupportedDependencies = [] - - requiredDependencies.forEach(dependencyArray => { - - if(dependencyArray.dependencies) { - dependencyArray.dependencies.map((dependency) => { - - if (!supportedDependencyMap.has(dependency.name)) unsupportedDependencies.push(dependency.name) - else injectionPackageMap.set(dependency.name, supportedDependencyMap.get(dependency.name)) + requiredDependencies.forEach((dependencyArray) => { + if (dependencyArray.dependencies) { + dependencyArray.dependencies.map((dependency) => { + if (!supportedDependencyMap.has(dependency.name)) + unsupportedDependencies.push(dependency.name) + else + injectionPackageMap.set( + dependency.name, + supportedDependencyMap.get(dependency.name) + ) + }) + } + if (unsupportedDependencies.length > 0) + throw `Package ${packageName} requires unsupported dependencies: [${unsupportedDependencies}]` + const packageEnvironmentVariables = {} + Object.keys(requiredEnvs).map((envVariable) => { + packageEnvironmentVariables[envVariable] = process.env[envVariable] }) - } - if (unsupportedDependencies.length > 0) - throw `Package ${packageName} requires unsupported dependencies: [${unsupportedDependencies}]` - - const packageEnvironmentVariables = {} - Object.keys(requiredEnvs).map((envVariable) => { - packageEnvironmentVariables[envVariable] = process.env[envVariable] + dependencyManager(injectionPackageMap, packageEnvironmentVariables) }) - - dependencyManager(injectionPackageMap, packageEnvironmentVariables) - - }); } } - - }); - + }) } catch (error) { console.log('Dependency Manager Error: ', error) throw error diff --git a/src/middlewares/routeConfigInjector.js b/src/middlewares/routeConfigInjector.js index 11f4b21..3a20016 100644 --- a/src/middlewares/routeConfigInjector.js +++ b/src/middlewares/routeConfigInjector.js @@ -9,12 +9,10 @@ exports.routeConfigInjector = (req, res, next) => { const routeConfig = routesConfigs.routes.find((route) => matchPathsAndExtractParams(route.sourceRoute, urlWithoutQuery) ) - if(routeConfig.targetPackages[0] && routeConfig.targetPackages[0].service){ + if (routeConfig.targetPackages[0] && routeConfig.targetPackages[0].service) { req['baseUrl'] = process.env[`${routeConfig.targetPackages[0].service.toUpperCase()}_SERVICE_BASE_URL`] - - }else { + } else { req['baseUrl'] = process.env[`${routeConfig.targetPackages[0].basePackageName.toUpperCase()}_SERVICE_BASE_URL`] - } req['type'] = routeConfig.type req['inSequence'] = routeConfig.inSequence diff --git a/src/package.json b/src/package.json index 22a7f46..26bf1bf 100644 --- a/src/package.json +++ b/src/package.json @@ -22,19 +22,11 @@ "cli-table": "^0.3.11", "cors": "^2.8.5", "dotenv": "^16.3.1", - "elevate-entity-management": "^1.0.7", - "elevate-kafka": "^1.0.7", - "elevate-mentoring": "^1.1.47", - "elevate-package-validator": "^1.0.0", - "elevate-project": "^1.1.9", - "elevate-scheduler": "^1.0.4", - "elevate-self-creation-portal": "^1.0.31", - "elevate-survey": "^1.0.15", - "elevate-user": "^1.1.77", "express": "^4.18.2", "express-rate-limit": "^7.2.0", "module-alias": "^2.2.3", - "request": "^2.88.2" + "request": "^2.88.2", + "shiksha-user": "^1.2.0" }, "devDependencies": { "eslint": "^8.16.0", diff --git a/src/scripts/fetchRouteConfigs.js b/src/scripts/fetchRouteConfigs.js index 2d14761..61d4f41 100644 --- a/src/scripts/fetchRouteConfigs.js +++ b/src/scripts/fetchRouteConfigs.js @@ -4,62 +4,60 @@ * name : fetchRouteConfigs.js * author : Adithya Dinesh * created-date : 04-Sep-2024 - * Description : Fetches routes from each service as provided in the .env file and creates routes config for each services. + * Description : Fetches routes from each service as provided in the .env file and creates routes config for each services. * Seperates all orchestrated calls in a different file. */ -// import requirements +// import requirements const request = require('../generics/request.js') const schema = require('../constants/routeSchema.js') const fs = require('fs').promises const path = require('path') const { execSync } = require('child_process') -const _ = require('lodash'); -const Ajv = require("ajv"); // for validating schema -const ajv = new Ajv(); +const _ = require('lodash') +const Ajv = require('ajv') // for validating schema +const ajv = new Ajv() -const currentDirectory = process.cwd(); //fetch the current working directory -// output dir to create files +const currentDirectory = process.cwd() //fetch the current working directory +// output dir to create files const outputDir = path.join(currentDirectory, 'configs', 'routesConfigs') //join path to routesConfigs folder const orchestratedFile = path.join(outputDir, 'orchestrated.json') //join path to orchestrated.json file let orchestratedFileData = { - routes: [] + routes: [], } /** * Main fuction which fetches the routes from env file and creates json file in './configs/routesConfigs' */ async function fetchRouteConfigs() { - try { - - try { - // Check if the directory exists - await fs.access(outputDir); - console.log(`outputDir ${outputDir} already exists.`); - } catch (error) { - // If access fails, it means the outputDir doesn't exist, so create it - await fs.mkdir(outputDir, { recursive: true }); - console.log(`outputDir ${outputDir} created.`); - } - // Fetch routes config file from env and split - const fetchRouteUrls = process.env.ROUTE_CONFIG_JSON_URLS_PATHS.split(","); - - // Loop through the URLs one by one - for (const fetchUrl of fetchRouteUrls) { - if (fetchUrl !== '') { - await constructJson(fetchUrl); // Wait for each URL to be processed sequentially - } - } - - // Write all the orchestrated routes to the file - if (orchestratedFileData.routes.length > 0) { - await handleOrchestratedRoutes(orchestratedFileData.routes); - } - - } catch (error) { - throw (error); - } + try { + try { + // Check if the directory exists + await fs.access(outputDir) + console.log(`outputDir ${outputDir} already exists.`) + } catch (error) { + // If access fails, it means the outputDir doesn't exist, so create it + await fs.mkdir(outputDir, { recursive: true }) + console.log(`outputDir ${outputDir} created.`) + } + // Fetch routes config file from env and split + const fetchRouteUrls = process.env.ROUTE_CONFIG_JSON_URLS_PATHS.split(',') + + // Loop through the URLs one by one + for (const fetchUrl of fetchRouteUrls) { + if (fetchUrl !== '') { + await constructJson(fetchUrl) // Wait for each URL to be processed sequentially + } + } + + // Write all the orchestrated routes to the file + if (orchestratedFileData.routes.length > 0) { + await handleOrchestratedRoutes(orchestratedFileData.routes) + } + } catch (error) { + throw error + } } /** @@ -67,107 +65,108 @@ async function fetchRouteConfigs() { * @param {String} url - The URL to fetch. */ async function constructJson(url) { - try { - let jsonData = {} - - if (isAValidUrl(url)) { - // get the data in json format - jsonData = await request.get(url) - } else if (await validateJsonFilePath(url)) { - // load the json file from mentioned location - jsonData.data = await loadJsonFile(url); - } - - jsonData.success = jsonData?.data.routes.length > 0 && isJsonValid(jsonData) ? true : false - - let fileData = { - routes: [] - } - - - if (jsonData.success) { - // extract base package name to create json file - const outputFile = path.join(outputDir, jsonData.data.routes[0]?.targetPackages[0]?.packageName + '.json') - - jsonData.data.routes.forEach(async (eachRoute) => { - if (!eachRoute.orchestrated) { - // If the API is not orchestrated, write it in the package-specific file - if (!isADuplicateRoute(eachRoute, fileData.routes) && await isAValidSchema(eachRoute, schema.passThroughRouteSchema)) { - fileData.routes.push(eachRoute); - } - } else { - if (await isAValidSchema(eachRoute, schema.orchestratedRouteSchema)) { - orchestratedFileData.routes.push(eachRoute); - } - } - }); - // Ensure the directory exists - const dir = path.dirname(outputDir); - await fs.mkdir(dir, { recursive: true }); - - // Write the JSON file (creates or overwrites the file) - await fs.writeFile(outputFile, JSON.stringify(fileData, null, 4)); - - console.log(`File generated : ' ${outputFile} '.`); - } - - } catch (error) { - console.error("Execution Halted : ", error) - throw (error) - } - + try { + let jsonData = {} + + if (isAValidUrl(url)) { + // get the data in json format + jsonData = await request.get(url) + } else if (await validateJsonFilePath(url)) { + // load the json file from mentioned location + jsonData.data = await loadJsonFile(url) + } + + jsonData.success = jsonData?.data.routes.length > 0 && isJsonValid(jsonData) ? true : false + + let fileData = { + routes: [], + } + + if (jsonData.success) { + // extract base package name to create json file + const outputFile = path.join(outputDir, jsonData.data.routes[0]?.targetPackages[0]?.packageName + '.json') + + jsonData.data.routes.forEach(async (eachRoute) => { + if (!eachRoute.orchestrated) { + // If the API is not orchestrated, write it in the package-specific file + if ( + !isADuplicateRoute(eachRoute, fileData.routes) && + (await isAValidSchema(eachRoute, schema.passThroughRouteSchema)) + ) { + fileData.routes.push(eachRoute) + } + } else { + if (await isAValidSchema(eachRoute, schema.orchestratedRouteSchema)) { + orchestratedFileData.routes.push(eachRoute) + } + } + }) + // Ensure the directory exists + const dir = path.dirname(outputDir) + await fs.mkdir(dir, { recursive: true }) + + // Write the JSON file (creates or overwrites the file) + await fs.writeFile(outputFile, JSON.stringify(fileData, null, 4)) + + console.log(`File generated : ' ${outputFile} '.`) + } + } catch (error) { + console.error('Execution Halted : ', error) + throw error + } } /** * Handles orchestrated calls, opens the orchestrated.json file , checks for duplicate and writes into the file. * @param {Object} newRoutes - New routes object */ const handleOrchestratedRoutes = async (newRoutes) => { - try { - const existingRoutes = await fs.readFile(orchestratedFile, 'utf8') - let fileWriteFlag = false - let routes = [] - try { - routes = JSON.parse(existingRoutes).routes || [] - } catch (error) { - routes = [] - } - - newRoutes.forEach(async (routeDetails) => { - if (!isADuplicateRoute(routeDetails, routes)) { - routes.push(routeDetails) - fileWriteFlag = true - } - }) - - if (fileWriteFlag) await fs.writeFile(orchestratedFile, JSON.stringify({ routes }, null, 4)); - - } catch (error) { - if (error.code === 'ENOENT') { - // if the file is not created , create - await fs.writeFile(orchestratedFile, JSON.stringify({ routes: newRoutes }, null, 4)); - console.log(`File generated : ' ${orchestratedFile} '`); - } else { - console.log("-----> error : ", error) - } - } + try { + const existingRoutes = await fs.readFile(orchestratedFile, 'utf8') + let fileWriteFlag = false + let routes = [] + try { + routes = JSON.parse(existingRoutes).routes || [] + } catch (error) { + routes = [] + } + + newRoutes.forEach(async (routeDetails) => { + if (!isADuplicateRoute(routeDetails, routes)) { + routes.push(routeDetails) + fileWriteFlag = true + } + }) + + if (fileWriteFlag) await fs.writeFile(orchestratedFile, JSON.stringify({ routes }, null, 4)) + } catch (error) { + if (error.code === 'ENOENT') { + // if the file is not created , create + await fs.writeFile(orchestratedFile, JSON.stringify({ routes: newRoutes }, null, 4)) + console.log(`File generated : ' ${orchestratedFile} '`) + } else { + console.log('-----> error : ', error) + } + } } // Function to check for duplicates in the routes function isADuplicateRoute(newItem, existingItems) { - try { - return _.some(existingItems, item => - item.sourceRoute === newItem.sourceRoute && - item.type === newItem.type && - item.priority === newItem.priority && - item.inSequence === newItem.inSequence && - item.orchestrated === newItem.orchestrated && - _.isEqual(item.targetPackages, newItem.targetPackages) && - _.isEqual(item.responseMessage, newItem.responseMessage) && - _.isEqual(item.rateLimit, newItem.rateLimit) - ); - } catch (error) { - if (error.name === 'TypeError') return false; - } + try { + return _.some( + existingItems, + (item) => + item.sourceRoute === newItem.sourceRoute && + item.type === newItem.type && + item.priority === newItem.priority && + item.inSequence === newItem.inSequence && + item.orchestrated === newItem.orchestrated && + _.isEqual(item.targetPackages, newItem.targetPackages) && + _.isEqual(item.responseMessage, newItem.responseMessage) && + _.isEqual(item.rateLimit, newItem.rateLimit) + ) + } catch (error) { + if (error.name === 'TypeError') return false + } } /** @@ -175,12 +174,12 @@ function isADuplicateRoute(newItem, existingItems) { * @param {String} path - URL path */ function isAValidUrl(path) { - try { - new URL(path); - return true; // Input is a valid URL - } catch (e) { - throw { message: `Invalid URL : ${path} ` } - } + try { + new URL(path) + return true // Input is a valid URL + } catch (e) { + throw { message: `Invalid URL : ${path} ` } + } } /** @@ -189,21 +188,19 @@ function isAValidUrl(path) { * @param {Object} schema - Pre-set schema */ async function isAValidSchema(newRoute, schema) { - try { - // Compile the schema - const validate = ajv.compile(schema); - - // Validate the data - const valid = validate(newRoute); - // Output the result - if (valid) return true - - throw { message: `Invalid Schema : ${newRoute} ` } - - } catch (error) { - throw error - } - + try { + // Compile the schema + const validate = ajv.compile(schema) + + // Validate the data + const valid = validate(newRoute) + // Output the result + if (valid) return true + + throw { message: `Invalid Schema : ${newRoute} ` } + } catch (error) { + throw error + } } /** @@ -211,18 +208,18 @@ async function isAValidSchema(newRoute, schema) { * @param {String} uri - File path */ async function validateJsonFilePath(uri) { - try { - // Resolve the absolute path - const absolutePath = path.resolve(uri); - - // Check if the path exists and is a file - const stats = await fs.lstat(absolutePath); - - return stats.isFile() && path.extname(absolutePath).toLowerCase() === '.json'; - } catch (error) { - // If an error occurs, it's not a valid local path or file - return false; - } + try { + // Resolve the absolute path + const absolutePath = path.resolve(uri) + + // Check if the path exists and is a file + const stats = await fs.lstat(absolutePath) + + return stats.isFile() && path.extname(absolutePath).toLowerCase() === '.json' + } catch (error) { + // If an error occurs, it's not a valid local path or file + return false + } } /** @@ -230,14 +227,14 @@ async function validateJsonFilePath(uri) { * @param {String} filePath - File path */ async function loadJsonFile(filePath) { - try { - const fileContent = await fs.readFile(filePath, 'utf8'); - return JSON.parse(fileContent); - } catch (error) { - throw { - message: `Failed to load Json file. File path : ${filePath} ` - }; - } + try { + const fileContent = await fs.readFile(filePath, 'utf8') + return JSON.parse(fileContent) + } catch (error) { + throw { + message: `Failed to load Json file. File path : ${filePath} `, + } + } } /** @@ -246,14 +243,14 @@ async function loadJsonFile(filePath) { */ function isJsonValid(jsonData) { - try { - typeof jsonData === "string" ? JSON.parse(jsonData) : ""; // Attempt to parse the JSON string - return true; // If parsing succeeds, it's a valid JSON - } catch (error) { - throw { - message: `Invalid Json : ${jsonData}` - } - } + try { + typeof jsonData === 'string' ? JSON.parse(jsonData) : '' // Attempt to parse the JSON string + return true // If parsing succeeds, it's a valid JSON + } catch (error) { + throw { + message: `Invalid Json : ${jsonData}`, + } + } } module.exports = { executeFetchRoutesScript } @@ -261,11 +258,10 @@ module.exports = { executeFetchRoutesScript } * Executes the functions in the script. */ async function executeFetchRoutesScript() { - try { - await fetchRouteConfigs() - console.log('Route fetch Script executed successfully.') - } catch (error) { - throw error.message || 'Error occurred while running the script' - - } + try { + await fetchRouteConfigs() + console.log('Route fetch Script executed successfully.') + } catch (error) { + throw error.message || 'Error occurred while running the script' + } }