Skip to content

Commit

Permalink
Added: Feature For load OpenAPIValidator Cache on app boot
Browse files Browse the repository at this point in the history
  • Loading branch information
shreyvishal committed Jun 18, 2024
1 parent af7e86f commit cb80785
Showing 1 changed file with 84 additions and 32 deletions.
116 changes: 84 additions & 32 deletions src/middlewares/schemaValidator.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import { Exception, ExceptionType } from "../models/exception.model";
import { Locals } from "../interfaces/locals.interface";
import { getConfig } from "../utils/config.utils";
import logger from "../utils/logger.utils";

import {
RequestActions,
ResponseActions
} from "../schemas/configs/actions.app.config.schema";
import httpMocks from "node-mocks-http";
import { v4 as uuid_v4 } from "uuid";
import { AppMode } from "../schemas/configs/app.config.schema";
import { GatewayMode } from "../schemas/configs/gateway.app.config.schema";
const protocolServerLevel = `${getConfig().app.mode.toUpperCase()}-${getConfig().app.gateway.mode.toUpperCase()}`;
const specFolder = "schemas";

Expand Down Expand Up @@ -58,18 +65,20 @@ export class OpenApiValidatorMiddleware {
`Intially cache Not found loadApiSpec file. Loading.... ${file}`
);
const apiSpec = this.getApiSpec(file);
const requestHandler = OpenApiValidator.middleware({
apiSpec,
validateRequests: true,
validateResponses: false,
$refParser: {
mode: "dereference"
}
});
OpenApiValidatorMiddleware.cachedOpenApiValidator[file] = {
apiSpec,
count: 0,
requestHandler: OpenApiValidator.middleware({
apiSpec,
validateRequests: true,
validateResponses: false,
$refParser: {
mode: "dereference"
}
})
requestHandler: requestHandler
};
initializeOpenApiValidatorCache(requestHandler);
}
}
} catch (err) {
Expand Down Expand Up @@ -129,6 +138,7 @@ export class OpenApiValidatorMiddleware {
OpenApiValidatorMiddleware.cachedOpenApiValidator[specFile]
.requestHandler;
}

const cacheStats = Object.entries(
OpenApiValidatorMiddleware.cachedOpenApiValidator
).map((cache) => {
Expand All @@ -146,13 +156,77 @@ export class OpenApiValidatorMiddleware {
}
}

const initializeOpenApiValidatorCache = async (stack: any) => {
let actions: string[] = [];
if (
(getConfig().app.mode === AppMode.bap &&
getConfig().app.gateway.mode === GatewayMode.client) ||
(getConfig().app.mode === AppMode.bpp &&
getConfig().app.gateway.mode === GatewayMode.network)
) {
actions = Object.keys(RequestActions);
} else {
actions = Object.keys(ResponseActions);
}
actions.forEach((action) => {
const mockRequest = (body: any) => {
const req = httpMocks.createRequest({
method: "POST",
url: `/${action}`,
headers: {
"Content-Type": "application/json",
Authorization: uuid_v4()
},
body: body
});

req.app = {
enabled: (setting: any) => {
if (
setting === "strict routing" ||
setting === "case sensitive routing"
) {
return true;
}
return false;
}
} as any;
return req;
};
const reqObj = mockRequest({ context: {}, message: {} });
walkSubstack(stack, reqObj, {}, () => {
return;
});
});
};

const walkSubstack = function (
stack: any,
req: any,
res: any,
next: NextFunction
) {
if (typeof stack === "function") {
stack = [stack];
}
const walkStack = function (i: any, err?: any) {
if (err) {
return schemaErrorHandler(err, req, res, next);
}
if (i >= stack.length) {
return next();
}
stack[i](req, res, walkStack.bind(null, i + 1));
};
walkStack(0);
};

export const schemaErrorHandler = (
err: any,
req: Request,
res: Response,
next: NextFunction
) => {
logger.error("OpenApiValidator Error", err);
if (err instanceof Exception) {
next(err);
} else {
Expand Down Expand Up @@ -207,29 +281,7 @@ export const openApiValidatorMiddleware = async (
}
}
}

const openApiValidator =
OpenApiValidatorMiddleware.getInstance().getOpenApiMiddleware(specFile);

const walkSubstack = function (
stack: any,
req: any,
res: any,
next: NextFunction
) {
if (typeof stack === "function") {
stack = [stack];
}
const walkStack = function (i: any, err?: any) {
if (err) {
return schemaErrorHandler(err, req, res, next);
}
if (i >= stack.length) {
return next();
}
stack[i](req, res, walkStack.bind(null, i + 1));
};
walkStack(0);
};
walkSubstack([...openApiValidator], req, res, next);
};

0 comments on commit cb80785

Please sign in to comment.