Skip to content

Commit

Permalink
added gzip handler specific to request middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
nitish-egov committed Dec 18, 2024
1 parent 05f3cbf commit 091aab3
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 26 deletions.
15 changes: 3 additions & 12 deletions health-services/project-factory/src/server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { tracingMiddleware } from "./tracing";
import { createProxyMiddleware } from "http-proxy-middleware";
import * as v8 from "v8";
import { logger } from "./utils/logger";
import { handleGzipRequest } from "./utils/gzipHandler";

const printMemoryInMB = (memoryInBytes: number) => {
const memoryInMB = memoryInBytes / (1024 * 1024); // Convert bytes to MB
Expand Down Expand Up @@ -42,17 +41,9 @@ class App {
}

private initializeMiddlewares() {
this.app.use((req, res, next) => {
const contentType = req.headers["content-type"];

if (contentType === "application/gzip") {
return handleGzipRequest(req, res, next);
}

return bodyParser.json({ limit: config.app.incomingRequestPayloadLimit })(req, res, next);
});


this.app.use(
bodyParser.json({ limit: config.app.incomingRequestPayloadLimit })
);
this.app.use(
bodyParser.urlencoded({
limit: config.app.incomingRequestPayloadLimit,
Expand Down
28 changes: 25 additions & 3 deletions health-services/project-factory/src/server/utils/gzipHandler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import zlib from "zlib";
import { Request, Response, NextFunction } from "express";
const { object, string } = require("yup"); // Importing object and string from yup for schema validation
import { logger } from "./logger";
import { errorResponder } from "./genericUtils";


const requestSchema = object({
apiId: string().nullable(), // Nullable string field for API ID
action: string().nullable(), // Nullable string field for action
msgId: string().required(), // Required string field for message ID
authToken: string().nullable(), // Nullable string field for authentication token
userInfo: object().nonNullable() // Non-nullable object field for user information
});

export const handleGzipRequest = (
req: Request,
Expand All @@ -13,6 +24,7 @@ export const handleGzipRequest = (
req.on("end", () => {
try {
const gzipBuffer = Buffer.concat(buffers);
logger.info("Gzip buffer size:", gzipBuffer.length);

// Decompress the Gzip data
zlib.gunzip(gzipBuffer, (err, decompressedBuffer) => {
Expand All @@ -24,10 +36,20 @@ export const handleGzipRequest = (

try {
// Convert the decompressed buffer to string and parse as JSON
const jsonData = decompressedBuffer.toString();
const jsonData = decompressedBuffer.toString().trim();
logger.info("Decompressed JSON data:", jsonData);
const parsedData = JSON.parse(jsonData);
req.body = parsedData; // Attach parsed data to the request body
next(); // Proceed to next middleware
req.body = parsedData;
// Validation 1: Check if tenantId is present
if (!req?.body?.RequestInfo?.userInfo?.tenantId) {
let e: any = new Error("RequestInfo.userInfo.tenantId is missing");
e = Object.assign(e, { status: 400, code: "VALIDATION_ERROR" });
return errorResponder(e, req, res, 400); // Return error response if tenantId is missing
}

// Validation 2: Validate the request payload against the defined schema
requestSchema.validateSync(req.body.RequestInfo); // Assuming validateSync is synchronous
next(); // Proceed to next middleware or controller if valid
} catch (parseError) {
logger.error("Error parsing JSON data:", parseError);
res.status(500).send("Invalid JSON in Gzip content");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextFunction, Request, Response } from "express"; // Importing necessar
const { object, string } = require("yup"); // Importing object and string from yup for schema validation
import { errorResponder } from "../genericUtils"; // Importing errorResponder function from genericUtils
import { logger } from "../logger";
import { handleGzipRequest } from "../gzipHandler";

// Defining the request schema using yup
const requestSchema = object({
Expand All @@ -25,18 +26,22 @@ const requestMiddleware = (req: Request, res: Response, next: NextFunction) => {
errorResponder(e, req, res, 415)
return;
}
// Check if tenantId is missing in RequestInfo.userInfo
if (!req?.body?.RequestInfo?.userInfo?.tenantId) {
// If tenantId is missing, throw Validation Error
let e: any = new Error("RequestInfo.userInfo.tenantId is missing");
e = Object.assign(e, { status: 400, code: "VALIDATION_ERROR" });
errorResponder(e, req, res, 400)
return;
if (contentType === 'application/gzip') {
return handleGzipRequest(req, res, next);
} else {
// Check if tenantId is missing in RequestInfo.userInfo
if (!req?.body?.RequestInfo?.userInfo?.tenantId) {
// If tenantId is missing, throw Validation Error
let e: any = new Error("RequestInfo.userInfo.tenantId is missing");
e = Object.assign(e, { status: 400, code: "VALIDATION_ERROR" });
errorResponder(e, req, res, 400)
return;
}
// Validate request payload against the defined schema
requestSchema.validateSync(req.body.RequestInfo);
// If validation succeeds, proceed to the next middleware
next();
}
// Validate request payload against the defined schema
requestSchema.validateSync(req.body.RequestInfo);
// If validation succeeds, proceed to the next middleware
next();
} catch (error) {
// If an error occurs during validation process, handle the error using errorResponder function
errorResponder(error, req, res);
Expand Down

0 comments on commit 091aab3

Please sign in to comment.