如何合并两个中间件并导出为一个?

Aya*_*yan 5 middleware node.js express

我有一个实用程序文件,它基本上有两个功能(一个用于检测用户位置,另一个用于获取用户设备详细信息)充当中间件。现在我想知道是否可以将两个中间件组合在一起,以便它可以与路线上的其他中间件一起使用。我还希望在需要时可以自由地单独使用实用程序文件中的功能。

实用程序文件

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 };
Run Code Online (Sandbox Code Playgroud)

示例路线

app.post("/v1/register", [getDeviceLocation, getDeviceClient, Otp.verify], User.create);

app.post("/v1/auth/google", [getDeviceLocation, getDeviceClient, Auth.verifyGoogleIdToken], Auth.useGoogle);  
Run Code Online (Sandbox Code Playgroud)

我想拥有getDeviceLocationgetDeviceClient组合成一个说getDeviceInfo但在任何路线上需要时可以自由使用getDeviceLocationgetDeviceClient单独使用。

Myk*_*lis 6

Express 允许您在 array 中声明中间件,因此您可以简单地定义要组合的中间件的数组:

const getDeviceLocation = async (req, res, next) => {
...
};

const getDeviceClient = async (req, res, next) => {
...
};

const getDeviceInfo = [getDeviceLocation, getDeviceClient];

module.exports = { getDeviceLocation, getDeviceClient, getDeviceInfo };
Run Code Online (Sandbox Code Playgroud)

然后,您可以在任意位置使用一个或两个中间件的任意组合:

app.use('/foo', getDeviceLocation, () => {});
app.use('/bar', getDeviceClient, () => {});
app.use('/baz', getDeviceInfo, () => {});
Run Code Online (Sandbox Code Playgroud)


Ram*_*rar 1

在你的情况下,也许你可以使用这样简单的东西

const getDeviceInfo = async (req, res, next) => {
    await getDeviceClient(req, res, async () => {
        await getDeviceLocation(req, res, next)
    })
}
Run Code Online (Sandbox Code Playgroud)

但您可能需要处理错误情况。