将中间件添加到单个路由Js Express的最干净的方法

时间:2019-03-07 10:28:33

标签: node.js express

我想知道我是否以最干净的方式做事。这是我的设置:

Files
  - app.js
  - routes.js
  - controllers
    - wallet.js

routes.js

const router = require('express').Router()
const wallet = require('./controllers/wallet')

router.post('/wallet/generate', wallet.generate)
router.get('/wallet/address', wallet.address)
router.get('/wallet/balance', wallet.balance)
router.post('/wallet/transfer', wallet.transfer)

module.exports = router

controllers/wallet.js

const generate = async (req, res) => {
  // ...
}

const address = async (req, res) => {
  // ...
}

const balance = async (req, res) => {
  // ...
}

const _transfer = async (req, res) => {
  // ...
}

const transfer = [
  // I put my subroute specific middlewares here
  handleInvalidAddress,
  handleInvalidAmount,
  handleInvalidTokenName,
  _transfer
]

module.exports = {transfer, generate, address, balance}

这是可接受的方式吗?我找不到可以建模的开源快递应用程序的任何好例子。在我看来,仅在routes.js文件中声明一条路由的小型中间件是错误的。所有逻辑都在controllers文件夹中,而中间件则是逻辑。

编辑:the transfer middlewares除了钱包转移路线外,它们不太可能在其他任何地方重复使用。在现实生活中,它们更大并且不应杂乱转移路线功能

const handleInvalidAddress = (req, res, next) => {
  if (req.body.address) {
    return next()
  }
  res.status(400).send('invalid address')
}

const handleInvalidAmount = (req, res, next) => {
  if (req.body.amount) {
    return next()
  }
  res.status(400).send('invalid amount')
}

const handleInvalidTokenName = (req, res, next) => {
  if (req.body.tokenName) {
    return next()
  }
  res.status(400).send('invalid token name')
}

1 个答案:

答案 0 :(得分:0)

这是定义新路由器的好方法,如上所示。如果中间件和路由处理程序功能不被重用,则可以就地使用它们。它不需要知道wallet部分,因为它对所有路由都是公用的:

const router = require('express').Router()

router.post('/generate', async (req, res) => {...})
router.get('/address', async (req, res) => {...})
router.get('/balance', async (req, res) => {...})


router.use('/transfer', function handleInvalidAddress(req, res, next) {...})
router.post('/transfer', async (req, res) => {...})

module.exports = router;

并像这样安装它:

const walletRouter = require('./routes/wallet')        
appRouter.use('/wallet', walletRouter);

如果出于某种原因(例如插件系统)需要在多个模块之间分配wallet路由,使用依赖注入可能会有所帮助:

module.exports = router => {
    router.post('/generate', async (req, res) => {...})
    router.get('/address', async (req, res) => {...})
    router.get('/balance', async (req, res) => {...})

    router.use('/transfer', function handleInvalidAddress(req, res, next) {...})
    router.post('/transfer', async (req, res) => {...})
};

并像这样安装它:

const walletRouter = Router();
require('./routes/wallet')(walletRouter);
appRouter.use('/wallet', walletRouter);