【发布时间】:2015-04-02 12:02:37
【问题描述】:
我有一个 ExpressJS 应用程序,它采用表单数据并执行以下操作: 1. 检查是否提供了所有必需的值, 2.验证数据是否有效, 3.向数据库中添加一条记录以获得唯一ID, 4.使用ID和数据调用单独的服务器, 5. 根据服务器的响应,使用响应的详细信息更新数据库记录。
我正在使用 mongoskin 作为数据库。
我的问题与我如何控制流程有关。本质上,我将上述每个步骤都编写为中间件函数,因为我需要在每个回调中调用 next() 成功(或 next(err) 错误)。
似乎我编写了太多中间件,应该能够将这些步骤分组到包含多个“子功能”的更大的中间件集合中,但我不确定如何在 Express 中执行此操作,因为我需要调用next() 每次异步函数调用完成时。是否有正确的方法来做到这一点,或者这种“每一步一个中间件”方法真的是运行它的正确方法吗?
编辑:根据要求发布一些代码。为简洁起见,这是部分代码:
function validateFields(req, res, next) {
//...
//iterate over req.body to confirm all fields provided
//...
if (allDataProvided) {
//...
//iterate over req.body to confirm all fields valid
//...
if (allDataValid) {
return(next());
} else {
return(next(err));
}
} else {
return(next(err));
}
},
//get an auto incrementing ID fields from a mongodb collection (counters)
function getNextID(req, res, next) {
counters.findAndModify(
{ _id: "receiptid" },
[['_id','asc']],
{ $inc: { seq: 1 } },
{},
function(err, doc) {
if (err) {
return next(err);
} else {
req.receiptid = doc.seq;
return next();
}
});
},
//insert a new record into the transaction collection (txns) using the new ID
function createTransaction(req, res, next) {
txns.insert(
{ _id : req.receiptid,
body : req.body,
status : "pending"},
{},
function(err, r) {
if (err) {
return next(err);
} else {
return next();
}
});
},
//process the data on the remote web service using the provider's API (remoteapi)
function processTransaction(req, res, next) {
remoteapi.processTransaction(
{ data: req.body,
receiptid: req.receiptid },
function(err, r) {
if (err) {
return next(err);
} else {
req.txnReceipt = r;
return next();
}
});
},
//update the record in the database collection (txns) with the server response
function updateDatabase(req, res, next) {
txns.updateById(req.receiptid,
{ $set :{status : "success",
receipt: req.txnReceipt }
}, function (err, r) {
if (err) {
return next(err);
} else {
return next();
}
});
}
由于目前具有上述功能,我使用这个中间件的路线是这样开始的:
router.post('/doTransaction',
validateFields,
getNextID,
createTransaction,
processTransaction,
updateDatabase,
function(req, res, next) { //...
似乎我应该能够创建一个中间件函数,它可以连续完成所有这些事情,而不必每个中间件都是单独的中间件,但由于每个中间件都有一个异步函数,我需要调用 next( ) 在结果回调中,这是我可以看到它工作的唯一方法。
谢谢 亚伦
【问题讨论】:
-
你好,如果你能在这里发布一些代码会很棒
标签: node.js express next mongoskin