Skip to content

Commit

Permalink
added gzip handler in middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
nitish-egov committed Dec 18, 2024
1 parent b373ac4 commit 05f3cbf
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 8 deletions.
17 changes: 13 additions & 4 deletions health-services/project-factory/src/server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ 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 @@ -41,16 +42,24 @@ class App {
}

private initializeMiddlewares() {
this.app.use(
bodyParser.json({ limit: config.app.incomingRequestPayloadLimit })
);
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.urlencoded({
limit: config.app.incomingRequestPayloadLimit,
extended: true,
})
);
this.app.use(bodyParser.json());
// this.app.use(bodyParser.json());
this.app.use(tracingMiddleware);
this.app.use(requestMiddleware);
this.app.use(errorLogger);
Expand Down
41 changes: 41 additions & 0 deletions health-services/project-factory/src/server/utils/gzipHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import zlib from "zlib";
import { Request, Response, NextFunction } from "express";
import { logger } from "./logger";

export const handleGzipRequest = (
req: Request,
res: Response,
next: NextFunction
) => {
const buffers: Buffer[] = [];

req.on("data", (chunk) => buffers.push(chunk));
req.on("end", () => {
try {
const gzipBuffer = Buffer.concat(buffers);

// Decompress the Gzip data
zlib.gunzip(gzipBuffer, (err, decompressedBuffer) => {
if (err) {
logger.error("Error decompressing Gzip file:", err);
res.status(500).send("Invalid Gzip file");
return;
}

try {
// Convert the decompressed buffer to string and parse as JSON
const jsonData = decompressedBuffer.toString();
const parsedData = JSON.parse(jsonData);
req.body = parsedData; // Attach parsed data to the request body
next(); // Proceed to next middleware
} catch (parseError) {
logger.error("Error parsing JSON data:", parseError);
res.status(500).send("Invalid JSON in Gzip content");
}
});
} catch (err) {
logger.error("Error processing Gzip content:", err);
res.status(500).send("Invalid Gzip content");
}
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ const requestMiddleware = (req: Request, res: Response, next: NextFunction) => {
logger.info(`RECEIVED A HTTP REQUEST :: URI :: ${req.url}`);
// Check if the content type is 'application/json'
const contentType = req.headers['content-type'];
if (!contentType || !contentType.split(';').map(part => part.trim()).includes('application/json')) {
// If content type is not 'application/json', throw Unsupported Media Type error
let e: any = new Error("Unsupported Media Type: Content-Type should be 'application/json'");
if (!contentType || !contentType.split(';').map(part => part.trim()).includes('application/json') && !contentType.split(';').map(part => part.trim()).includes('application/gzip')) {
// If content type is not 'application/json' or 'application/gzip', throw Unsupported Media Type error
let e: any = new Error("Unsupported Media Type: Content-Type should be 'application/json' or 'application/gzip'");
e = Object.assign(e, { status: 415, code: "UNSUPPORTED_MEDIA_TYPE" });
errorResponder(e, req, res, 415)
return;
Expand All @@ -43,4 +43,4 @@ const requestMiddleware = (req: Request, res: Response, next: NextFunction) => {
}
};

export default requestMiddleware; // Exporting the requestMiddleware function for use in Express middleware chain
export default requestMiddleware; // Exporting the requestMiddleware function for use in Express middleware chain

0 comments on commit 05f3cbf

Please sign in to comment.