please review this code and handle the errors gracefully and make this robust
const express = require("express");
const http = require("http");
const cors = require("cors");
const bodyParser = require("body-parser");
const methodOverride = require("method-override");
const LockManager = require("node-locksmith");
const HttpService = require("../../../services/HTTPService");
const createLogger = require("../../../services/Logger");
const lockManager = new LockManager("medics_lab_result_receiver.lock");
// Initializes termination event handlers for graceful application shutdown.
lockManager.initializeTerminationHandlers();
const { convertBufferToBase64 } = require("../../../services/FileService");
// Create the application
const app = (module.exports = express());
// Setup Logger
const logger = createLogger("LabResultReceiver");
// PORT number to listen on
const PORT = 3462;
// Attach logger to the app
app.logger = logger;
// Add middleware necessary for REST APIs
app.use(cors());
app.use(methodOverride("X-HTTP-Method-Override"));
app.use(
bodyParser.json({
limit: "10mb",
})
);
app.use(
bodyParser.urlencoded({
limit: "10mb",
extended: true,
parameterLimit: 10000,
})
);
// CORS Support
app.use(function (req, res, next) {
logger.info("Processing request:", req.url);
if (req.body && Object.keys(req.body).length > 0) {
logger.info("Request Body:", req.body);
}
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH");
if (req.method === "OPTIONS") {
return res.status(200).json({});
} else {
next();
}
});
// Error handling middleware
app.use(function (err, req, res, next) {
if (err.name === "UnauthorizedError") {
res.status(401);
res.json({
message: err.name + ": " + err.message,
});
} else {
logger.error(err.stack);
res.status(500);
res.json({
message: "Internal Server Error",
});
}
});
async function postResult(labResult) {
try {
const response = await HttpService.post(
"http://localhost:3000/grid/api/lab/labResult",
labResult,
logger
);
console.log("<<< Response:", response);
return true;
} catch (error) {
console.log("*** Error:", error.message);
return false;
}
}
const interface = require('../adapters/index');
app.post("/api/lab/AcceptLabResults", async function (req, res) {
console.log("*** Lab Result received ..... ");
console.log(" Request body = " + JSON.stringify(req.body));
// @@ A hack since there is no other distiguishing attribute between the two
// @@ callers
if (req.body.ResultData) {
// Assuming this is IPlatina
return interface.IPLATINA.receiveLabResult(req, res, postResult);
} else if (req.body.ThirdPartyResultDataList) {
return interface.NEULIMS.receiveLabResult(req, res, postResult);
}
});
async function postSampleReceived(order) {
try {
const response = await HttpService.post(
http://localhost:3462/grid/api/lab/labOrder/${order.OrderNo}/sampleReceived,
null,
logger
);
console.log("<<< Response:", response);
return true;
} catch (error) {
console.log("*** Error:", error.message);
return false;
}
}
app.post("/api/lab/AcceptSampleNotification", async function (req, res) {
try {
console.log("*** Sample Accepted Notification received ..... ");
console.log(" Request body = " + JSON.stringify(req.body));
const orderList = req.body.OrderList;
if (!validateData(orderList, res, "Missing OrderList")) {
return;
}
const responseList = [];
for (const order of orderList) {
const status = await postSampleReceived(order);
responseList.push({
OrderNo: order.OrderNo,
LabID: order.LabID,
Status: status ? "SUCCESS" : "FAILED",
StatusMessage: status
? "Status update successful"
: "Sample acceptance failed",
StatusCode: status ? 1 : 2,
});
}
res.status(200);
res.json({
Status: responseList,
});
} catch (error) {
console.error(
"Error during Sample Notification processing:",
error.message ? error.message : error
);
res.status(500);
res.json({
Status: "FAILED",
StatusMessage: "Internal Server Error",
StatusCode: 1,
});
}
});
// Set up multer for handling form data
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.post('/api/lab/accept-lab-reports', upload.single('file'), async (req, res) => {
try {
const file = req.file;
logger.info('Parsed JSON Data:', req.body.data);
if (!file) {
const errMsg = 'No file uploaded';
logger.error('Validation Error:', errMsg);
return res.status(400).json({ error: errMsg });
}
logger.info(`Uploaded File Details - Name: ${file.originalname}, Size: ${file.size} bytes`);
const jsonData = JSON.parse(req.body.data);
const { orderId, LabID, reportStatus } = jsonData;
if (!orderId || !LabID) {
const errMsg = 'orderId and LabID are required';
logger.error('Validation Error:', errMsg);
return res.status(400).json({ error: errMsg });
}
logger.info('Validation successful. Processing file...');
const fileBase64String = await convertBufferToBase64(file.buffer, logger);
logger.info('File converted to base64 successfully.');
try {
const response = await postReceivedAttachment(orderId, LabID, fileBase64String);
if (response) {
logger.info('Lab Result Attachment processed successfully.');
// Send success response
return res.status(200).json({
Status: 'SUCCESS',
StatusCode: 0,
});
}
} catch (error) {
throw new Error(`Lab Result Attachment posting failed: ${error}`);
}
} catch (error) {
logger.error('Error during Lab Result Attachment processing:', error.message || error);
// Send error response
res.status(500).json({
Status: 'FAILED',
StatusMessage: error.message || 'Internal Server Error',
StatusCode: 1,
});
}
});
async function postReceivedAttachment(labOrderNumber, externalLabId, file) {
try {
const encodedFile = file;
const lra = {
orderNumber: labOrderNumber,
externalLabId: externalLabId,
reportFile: encodedFile
};
const response = await HttpService.post(`http://localhost:3462/grid/api/lab/labResult/${labOrderNumber}/uploadResultAttachment`, lra, {}, logger);
return response;
} catch (error) {
logger.error('*** Error:', error.message);
throw error;
}
}
/**
-
Initialize the Lab Result Receiver.
-
This function handles the setup of the application, including database connection(if any), middleware,
-
error handling, and HTTP server creation.
*/
async function initializeApp() {
try {
// Check for lock
await lockManager.checkLock();
// Create the lock with a timeout and retries of specified intervals
await lockManager.createLock(Infinity, 3);
process.on("unhandledRejection", (error, promise) => {
logger.error("Unhandled Promise Rejection:", error);
});
logger.info(`HTTP server is listening on port: ${PORT}`);
http.createServer(app).listen(PORT);
} catch (error) {
logger.error("Initialization error:", error);
process.exit(1);
}
}
// Call the async function to initialize the app
initializeApp();