diff --git a/package-lock.json b/package-lock.json index d3dc994..94e6133 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,6 +24,7 @@ "uuid": "^8.3.2", "winston": "^3.7.2", "winston-daily-rotate-file": "^4.7.1", + "yaml": "^2.4.2", "zod": "^3.14.2" }, "devDependencies": { @@ -4726,6 +4727,17 @@ "node": ">=0.4" } }, + "node_modules/yaml": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.4.2.tgz", + "integrity": "sha512-B3VqDZ+JAg1nZpaEmWtTXUlBneoGx6CPM9b0TENK6aoSu5t73dItudwdgmi6tHlIZZId4dZ9skcAQ2UbcyAeVA==", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/yn": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", diff --git a/package.json b/package.json index 929fc88..9af117f 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "uuid": "^8.3.2", "winston": "^3.7.2", "winston-daily-rotate-file": "^4.7.1", + "yaml": "^2.4.2", "zod": "^3.14.2" } } diff --git a/src/middlewares/schemaValidator.middleware.ts b/src/middlewares/schemaValidator.middleware.ts index 2bd4c78..d898249 100644 --- a/src/middlewares/schemaValidator.middleware.ts +++ b/src/middlewares/schemaValidator.middleware.ts @@ -5,8 +5,24 @@ import { Locals } from "../interfaces/locals.interface"; import { getConfig } from "../utils/config.utils"; import fs from "fs"; import path from "path"; +import { OpenAPIV3 } from 'express-openapi-validator/dist/framework/types'; +import YAML from 'yaml'; const protocolServerLevel = `${getConfig().app.mode.toUpperCase()}-${getConfig().app.gateway.mode.toUpperCase()}`; +// Cache object +const apiSpecCache: { [filename: string]: OpenAPIV3.Document } = {}; + +// Function to load and cache the API spec +const loadApiSpec = (specFile: string): OpenAPIV3.Document => { + if (!apiSpecCache[specFile]) { + console.log("Cache Not found. Loading....", specFile) + const apiSpecYAML = fs.readFileSync(specFile, 'utf8'); + const apiSpec = YAML.parse(apiSpecYAML); + apiSpecCache[specFile] = apiSpec; + } + return apiSpecCache[specFile]; +}; + export const schemaErrorHandler = ( err: any, req: Request, @@ -65,7 +81,7 @@ export const openApiValidatorMiddleware = async ( } const openApiValidator = OpenApiValidator.middleware({ - apiSpec: specFile, + apiSpec: loadApiSpec(specFile), validateRequests: true, validateResponses: false, $refParser: {