Nodejs最佳实践封装发送中间件
Nodejs best practice encapsulating send 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)
也许我只是以错误的方式处理了这种情况?
你怎样才能让它变得更好?
在这种情况下,使用 express 中间件概念(调用 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()
)作为错误路径。
好的,所以我目前正在学习更多 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)
也许我只是以错误的方式处理了这种情况?
你怎样才能让它变得更好?
在这种情况下,使用 express 中间件概念(调用 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()
)作为错误路径。