@fran-834/gs-microservice-core
Version:
Core package for Node.js microservices by Galduria Software. Includes security, logging, validation, and error handling middlewares.
43 lines (42 loc) • 1.58 kB
JavaScript
import express from "express";
import cors from "cors";
import { v4 as uuidv4 } from "uuid";
import helmet from "helmet";
import morganMiddleware from "./helpers/logger/morganMiddleware.js";
import { logError, logInfo } from "./helpers/logger/logOperation.js";
import { setAuthSecret } from "./config/auth.config.js";
/**
* Configures the Galduria microservice by setting up middleware for security, logging, and request ID.
*/
const setupCoreMiddlewares = (app, { gateway, jwtSecret, helmetConfig, corsOptions }) => {
try {
/**
* Middleware to assign a unique ID to each request.
*/
function assignId(req, res, next) {
if (req.headers["x-transaction-id"]) {
const id = req.headers["x-transaction-id"];
req.id = typeof id === "string" ? id : Array.isArray(id) ? id[0] : undefined;
}
else {
req.id = uuidv4();
}
next();
}
app.use(assignId);
// Morgan middleware (includes Winston for logging)
app.use(morganMiddleware);
if (!gateway)
app.use(express.json());
app.use(cors(corsOptions || {}));
app.use(helmet(helmetConfig || {}));
app.disable("x-powered-by");
setAuthSecret(jwtSecret ? jwtSecret : "");
logInfo("Galduria microservice configured successfully.");
}
catch (error) {
logError(undefined, error);
throw error; // Re-throw the error to be handled by the caller
}
};
export default setupCoreMiddlewares;