Node.js ExpressJS连接到回调的多个中间件
我有一个ExpressJS应用程序,它采用表单数据并执行以下操作: 1.检查是否提供了所有必需的值, 2.验证数据是否有效, 3.将记录添加到数据库以获取唯一ID, 4.使用ID和数据调用单独的服务器, 5.服务器响应后,使用响应的详细信息更新数据库记录 我用mongoskin做数据库 我的问题与我如何控制流量有关。基本上,我已经将上面的每个步骤作为一个中间件函数编写,因为我需要在每次回调成功时调用next()(或在出错时调用next(err)) 似乎我编写了太多的中间件,应该能够将这些步骤分组到包含多个“子函数”的更大的中间件集合中,但我不确定如何在Express中实现这一点,因为每次异步函数调用完成时,我都需要调用next()。有没有一种正确的方法可以做到这一点,或者这种“每一步一个中间件”的方法真的是运行这种方法的正确方法吗 编辑:根据要求发布一些代码。为了简洁起见,这是部分代码:Node.js ExpressJS连接到回调的多个中间件,node.js,express,next,mongoskin,Node.js,Express,Next,Mongoskin,我有一个ExpressJS应用程序,它采用表单数据并执行以下操作: 1.检查是否提供了所有必需的值, 2.验证数据是否有效, 3.将记录添加到数据库以获取唯一ID, 4.使用ID和数据调用单独的服务器, 5.服务器响应后,使用响应的详细信息更新数据库记录 我用mongoskin做数据库 我的问题与我如何控制流量有关。基本上,我已经将上面的每个步骤作为一个中间件函数编写,因为我需要在每次回调成功时调用next()(或在出错时调用next(err)) 似乎我编写了太多的中间件,应该能够将这些步骤分组
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) { //...
router.post('/doTransaction',
validateFields,
function(req, res, next) { //...
看起来我应该能够创建一个中间件函数,它可以连续完成所有这些事情,而不必每个都是一个单独的中间件,但是由于每个中间件中都有一个异步函数,我需要在结果回调中调用next(),这是我能看到它工作的唯一方式
谢谢
Aaron在一个中间件中实现所有步骤相当容易。我在下面包含了一些伪代码(它对代码的结构做出了各种假设,因为您没有提供实现细节,但只是给出了一个想法) 它使用包来“捕获”响应
var onHeaders = require('on-headers')
// Your middleware function
app.use(function(req, res, next) {
// Update the database when the response is being sent back.
onHeaders(res, function() {
// Do database update if we have a document id.
if (req._newDocumentId) {
db.collection.update(req._newDocumentId, data, function() {
// can't do a lot here!
});
}
});
// Perform the requires steps
if (! checkValuesAreSupplied(req)) {
return next(new Error(...));
}
if (! validateValues(req)) {
return next(new Error(...));
}
// Insert into database.
db.collection.insert(data, function(err, doc) {
if (err) return next(err);
...process the newly created doc...
// Store _id in the request for later.
req._newDocumentId = doc._id;
// Make the call to the separate server
makeCallToOtherServer(otherData, function(err, response) {
if (err) return next(err);
...process response...
return next();
});
});
});
您可以将所有内容放在一个模块中,只需使用回调就可以完成每个步骤,但在这种情况下,您可以得到“回调地狱” 所以我可以提出我认为更好的方法 使用此库,您的代码将如下所示:
function allInOneMiddleware(req, res, next) {
async.waterfall([
function (callback) {
validateFields(req, res, callback);
},
getNextID,
createTransaction,
processTransaction,
updateDatabase
], function (err) {
if (err) {
return next(err);
}
// response?
});
}
function validateFields(req, res, callback) {
//...
//iterate over req.body to confirm all fields provided
//...
if (allDataProvided) {
//...
//iterate over req.body to confirm all fields valid
//...
if (allDataValid) {
return callback(null, req.body);
}
return callback(err);
}
return callback(err);
}
//get an auto incrementing ID fields from a mongodb collection (counters)
function getNextID(body, callback) {
counters.findAndModify(
{_id: "receiptid"},
[['_id', 'asc']],
{$inc: {seq: 1}},
{},
function (err, doc) {
if (err) {
return callback(err);
}
callback(null, body, doc.seq);
});
}
//insert a new record into the transaction collection (txns) using the new ID
function createTransaction(body, receiptid, callback) {
txns.insert(
{
_id: receiptid,
body: body,
status: "pending"
},
{},
function (err, r) {
if (err) {
return callback(err);
}
callback(null, body, receiptid);
});
}
//process the data on the remote web service using the provider's API (remoteapi)
function processTransaction(body, receiptid, callback) {
remoteapi.processTransaction(
{
data: body,
receiptid: receiptid
},
function (err, r) {
if (err) {
return callback(err);
}
callback(null, receiptid, r);
});
}
//update the record in the database collection (txns) with the server response
function updateDatabase(receiptid, txnReceipt, callback) {
txns.updateById(receiptid,
{
$set: {
status: "success",
receipt: txnReceipt
}
}, callback);
}
谢谢Nicolai和robertklep的回答。虽然我认为这两个答案都能回答这个问题,但当我自己努力解决这个问题时,我意识到我没有看到森林而不是树木 我可以通过每个回调函数传递下一个函数,直到到达最后一个并调用它以将控件传递回中间件堆栈。这也允许我在这些函数中调用next(err) 因此,我的答案与Nicolai概述的概念非常相似,只是我不认为在这种情况下需要使用异步包,因为我不觉得这种特殊情况会让我陷入地狱 以下是我对自己问题的回答:
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) {
getNextID(req, res, 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;
createTransaction(req, res, 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 {
processTransaction(req, res, 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;
updateDatabase(req, res, 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();
}
});
}
因此,我不必在每个异步函数成功完成时调用next(),也不必为下一步编写另一个中间件,而是将next传递给下一个函数,直到需要它为止
这就是,我可以调用第一个函数作为我的中间件,如下所示:
router.post('/doTransaction',
validateFields,
getNextID,
createTransaction,
processTransaction,
updateDatabase,
function(req, res, next) { //...
router.post('/doTransaction',
validateFields,
function(req, res, next) { //...
然后,在每个操作完成时,依次调用其余步骤。您好,如果您能在这里发布一些代码,那就太好了