Node.js封装发送中间件的最佳实践

时间:2018-07-13 18:02:49

标签: node.js middleware

好,所以我目前正在学习更多的node.js,并决定在我创建的一个小型api中尝试一些基本的中间件。我想知道如何包装成功的请求。这是我的方法。

示例控制器

exports.getTask = async function (req, res, next) {
    try {
        const task = await db.Task.findOne(
            {
                where: {
                    id: req.params.taskId,
                    userId: req.params.userId
                }
            });
        if (task) {
            req.locals.data = task;
            res.status(httpStatus.OK);
            next();
        }
        res.status(httpStatus.NOT_FOUND);
        next();
    } catch (err) {
        next(err);
    }
};

中间件

exports.success = function(req, res, next) {
    const success = res.statusCode < 400;
    const successResponse = {
        timestamp: new Date().toUTCString(),
        success: success,
        status: res.statusCode
    };

    if (success) {
        successResponse.data = req.locals.data;
    }
    res.send(successResponse);
    next();
};

我认为不必为每个请求都设置req.locals.data然后打电话给下一个res.status(status),这可能不是我以错误的方式来处理这种情况吗?

您如何使它变得更好?

1 个答案:

答案 0 :(得分:0)

在这种情况下,可能使用明确的中间件概念(调用next())会显得过分。

我将通过为成功路径创建一个抽象来实现这一目标。考虑这样的事情:

const resWithSuccess = (req, res, data) => {
    res.json({
      data: data,
      timestamp: new Date().toUTCString(),
      // success: res.statusCode < 400, // --> actually you don't need this,
      //                                       since it will always be true
      // status: res.statusCode // --> or whatever else "meta" info you need
    });
};

然后,一旦您需要成功做出回应,那就去做吧

exports.getTask = async function (req, res, next) {
    // .... bla bla
    if (task) {
        resWithSuccess(tank);
    }
};

PS:...并且您可以使用快速中间件概念(调用next())作为错误路径。