gpt4 book ai didi

javascript - 在 NodeJS 中重用变量

转载 作者:行者123 更新时间:2023-12-03 03:45:15 26 4
gpt4 key购买 nike

我正在尝试使用(记录)函数的返回对象而不声明多个变量

如何按照 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)

最佳答案

我认为您问的是如何在配置每个路由的结果上调用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)
}

关于javascript - 在 NodeJS 中重用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45419122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com