I have a utility file which basically has two functions (one to detect user location and another to get user device details) acting as middlewares. Now I would like to know whether it is possible to combine both the middlewares together as one so that it could be used with other middlewares on the route. I would also like to have the freedom of using the functions in the utility file individually when required.
Utility file
const axios = require("axios");
const requestIp = require("request-ip");
const getDeviceLocation = async (req, res, next) => {
try {
// ToDO: Check if it works on production
const clientIp = requestIp.getClientIp(req);
const ipToCheck = clientIp === "::1" || "127.0.0.1" ? "" : clientIp;
const details = await axios.get("https://geoip-db.com/json/" + ipToCheck);
// Attach returned results to the request body
req.body.country = details.data.country_name;
req.body.state = details.data.state;
req.body.city = details.data.city;
// Run next middleware
next();
}
catch(error) {
return res.status(500).json({ message: "ERROR_OCCURRED" });
}
};
const getDeviceClient = async (req, res, next) => {
const userAgent = req.headers["user-agent"];
console.log("Device UA: " + userAgent);
next();
};
module.exports = { getDeviceLocation, getDeviceClient };
Example Routes
app.post("/v1/register", [getDeviceLocation, getDeviceClient, Otp.verify], User.create);
app.post("/v1/auth/google", [getDeviceLocation, getDeviceClient, Auth.verifyGoogleIdToken], Auth.useGoogle);
I would like to have getDeviceLocation
and getDeviceClient
combined into one say getDeviceInfo
yet have the freedom to use getDeviceLocation
and getDeviceClient
individually when required on any route.