多个中间件我有一个ExpressJS应用这需要形式的数据并执行以下操作: 1.检查所需的所有值被提供, 2.验证数据是有效的, 3.将记录添加到数据库以获得唯一的ID, 4.使用ID和数据调用单独的服务器, 5.根据来自服务器的响应,更新数据库记录并提供响应的详细信息。ExpressJS连接到回调
我使用mongoskin作为数据库。
我的问题与我如何控制流量有关。基本上我已经将上述每个步骤都写成了中间件函数,因为我需要在每个回调函数上调用next()成功(或者下一个错误)。
看来我正在编写太多的中间件,应该能够将这些步骤分组到更大的包含多个'子函数'的中间件集合中,但我不知道如何在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(),这是只有这样我才能看到它的工作。
感谢 亚伦
你好,如果你在这里发布一些代码会很好 – Nicolai 2015-04-02 12:52:18