javascriptnode.jsloggingrouterbunyan

Resuse a variable in NodeJS


I am trying to use(log) the return object of a function without decalring multiple variables

How best can this be done following nodeJS/Javascript best practice.

Do I have to declare this variable multiple times as I know it by reference.

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)

Solution

  • I think you're asking how to call logger.configured on the result of configuring each route without declaring more variables. One solution is to use anonymous functions to represent a route configuration:

    //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)
    }