功能性方法
我认为一个好的结构是尝试
currying
你的中间件。这是由中间件(如
body-parser
内部通过表达自己
serve-static
. 这样,你只需要一次,然后通过
db
你需要的地方,而不是你不需要的地方:
// Instead of declaring each function directly as a middleware function,
// we declare them as a function that returns a middleware function
function doesNotNeedDbParam () {
return function (req, res, next) {
â¦
}
}
function needsDbParam (db) {
return function (req, res, next) {
// You can use db here along with req, res, next
}
}
// No need to export a function now
module.exports = {
doesNotNeedDbParam,
needDbParam,
};
那么,只需要:
const middleware = require('./middleware');
â¦
router.use(middleware.doesNotNeedDbParam()); // Since this doesn't need anything, no argument
router.use(middleware.needsDbParam(db)); // You can pass db here now
如果您熟悉ES6+语法,可以将其浓缩为:
const doesNotNeedDbParam = () => (req, res, next) => {
â¦
}
const needsDbParam = (db) => (req, res, next) => {
// Use db here
}
// Export object here...
然后:
const { doesNotNeedDbParam, needsDbParam } = require('./middleware');
â¦
router.use(doesNotNeedDbParam());
router.use(needsDbParam(db));
附加进近
还有另一种方法可以做到这一点,将属性附加到
req
对象
一旦
. 这样就不需要重新打包
分贝
每次你想要的时候。许多其他软件包使用这种策略。就像这样:
function attachDb (db) { // Still use curry approach here since we want db
return function (req, res, next) {
// Attaches the specified db to req directly
req.db = db;
}
}
function needsDbParam (req, res, next) { // No need for currying
// Now use req.db here
}
// Export your other middlewareâ¦
然后,像这样使用,确保
attachDb
是
第一
以便在使用该属性之前对其进行分配:
router.use(attachDb(db)); // Before all other middleware that depend on req.db
â¦
// No need to call because this is already the middleware function,
// able to use req.db, which was assigned via attachDb
router.use(needDbParam);