我试图使用(log)函数的返回对象而不去除多个变量
在nodeJS
/ Javascript
最佳做法后,如何做到最好。
我必须多次声明这个变量,因为我知道它是参考。
var configuredRoute;
configuredRoute = router.route('/api/v1/people')
.get(PersonController.all)
.post(PersonController.add)
logger.configured(configuredRoute.methods,configuredRoute.path)
configuredRoute = router.route('/api/v1/people/:id')
.get(PersonController.getOne)
.put(PersonController.update)
.delete(PersonController.remove)
logger.configured(configuredRoute.methods,configuredRoute.path)
configuredRoute = router.route('/api/v1/supervisor')
.get(auth.isAuthenticated(), PersonController.allSupervisors)
logger.configured(configuredRoute.methods,configuredRoute.path)
configuredRoute = router.route('/api/v1/people/status/:phone')
.get(PersonController.isRegistered)
logger.configured(configuredRoute.methods,configuredRoute.path)
答案 0 :(得分:1)
我认为你在询问如何在不声明更多变量的情况下调用logger.configured
来配置每条路线的结果。一种解决方案是使用匿名函数来表示路由配置:
//assuming logger and router are declared in this scope
function configureRoute(route) {
const {methods, path} = route(router)
logger.configured(methods, path)
}
const routes = [
router =>
router.route('/api/v1/people')
.get(PersonController.all)
.post(PersonController.add),
router =>
router.route('/api/v1/people/:id')
.get(PersonController.getOne)
.put(PersonController.update)
.delete(PersonController.remove),
router =>
router.route('/api/v1/supervisor')
.get(auth.isAuthenticated(), PersonController.allSupervisors),
router =>
router.route('/api/v1/people/status/:phone')
.get(PersonController.isRegistered)
]
for (const route of routes) {
configureRoute(route)
}