Cat*_*ish 1 javascript middleware node.js express
我有一个Express应用程序,我正在尝试将所有中间件放在自己的文件中.一些中间件函数需要该db对象,而另一些则不需要.
这对于那些不需要的功能非常简单的db对象,但由于我下面的代码结构,我怎么可以参照db对象doesNotNeedDbParam,因为它已经拥有PARAMS req,res和next?
somefile.js:
const router = express.Router()
const doesNotNeedDbParam = require('./middleware')().doesNotNeedDbParam
function foo () {
// Currently I have to call require and pass in the db object here b/c
// it's not set when requiring the function doesNotNeedDbParam
router.use(require('./middleware')(db).needsDbParam // <-- Is there a better way to do this so that I can require the file above and pass the db object in when it's set?
}
// Setup db object here
foo()
Run Code Online (Sandbox Code Playgroud)
middleware.js
function doesNotNeedDbParam (req, res, next) {
...
}
function needsDbParam (req, res, next) {
// Where do I reference the db variable?
}
module.exports = (db) => {
return {
doesNotNeedDbParam: doesNotNeedDbParam,
needsDbParam: needsDbParam
}
}
Run Code Online (Sandbox Code Playgroud)
我认为一个好的结构,这是试图讨好你的中间件.这是一种由中间件实现的模式,例如body-parserExpress本身和内部使用的模式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,
};
Run Code Online (Sandbox Code Playgroud)
然后,只需要:
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
Run Code Online (Sandbox Code Playgroud)
如果您对ES6 +语法感到满意,可以缩写为:
const doesNotNeedDbParam = () => (req, res, next) => {
…
}
const needsDbParam = (db) => (req, res, next) => {
// Use db here
}
// Export object here...
Run Code Online (Sandbox Code Playgroud)
然后:
const { doesNotNeedDbParam, needsDbParam } = require('./middleware');
…
router.use(doesNotNeedDbParam());
router.use(needsDbParam(db));
Run Code Online (Sandbox Code Playgroud)
通过将属性附加到req对象一次,还有另一种方法可以做到这一点.这样就无需db每次都需要重新进行修复.许多其他包使用此策略.它是这样的:
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…
Run Code Online (Sandbox Code Playgroud)
然后,像这样使用它,确保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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |