How do I declare these variables globally in my controller?

Viewed 45

I have variables 'startDate' and 'endDate' which have the same definition across all 10 routes I have in my controller (NodeJS / Express).

How can I declare these globally so they don't have to be declared numerous times in each route?

My current code checks to see if startDate has been sent as part of the request from the page, otherwise sets the startDate using momentJS.

Currently, If I simply put the variables above the routes I get an error stating .req is not defined.

I'm fairly new to JS so any help would be appreciated.

Cheers

var express = require('express');
var router = express.Router();
var ccmQueuePerformance = require('../models/ccmQueuePerformance');
var moment = require('moment');


// Get hourly data by queue 

router.get('/callsOfferedByQueue', async function(req, res, next) {
    try {

        // Declare startDate and endDate

    var startDate = moment().startOf('month').format('YYYY-MM-DD');
    if(req.query.startDate) startDate = moment(req.query.startDate, 'YYYY-MM-DD').startOf('day');
    var endDate = moment().endOf('month').format('YYYY-MM-DD');
    if(req.query.endDate) endDate = moment(req.query.endDate, 'YYYY-MM-DD').startOf('day');
1 Answers

If they're dependent on req, they can't just be defined once because you have to take the individual request into account; but if the logic is identical between routes, the usual solution is to isolate that logic into a function and call it. For instance:

function getDates(req) {
    var startDate = moment().startOf('month').format('YYYY-MM-DD');
    if(req.query.startDate) startDate = moment(req.query.startDate, 'YYYY-MM-DD').startOf('day');
    var endDate = moment().endOf('month').format('YYYY-MM-DD');
    if(req.query.endDate) endDate = moment(req.query.endDate, 'YYYY-MM-DD').startOf('day');
    return { startDate, endDate };
}

or reworking the logic a bit:

function getDates(req) {
    return {
        startDate: req.query.startDate
                   ? moment(req.query.startDate, 'YYYY-MM-DD').startOf('day')
                   : moment().startOf('month').format('YYYY-MM-DD'),
        endDate:   req.query.endDate
                   ? moment(req.query.endDate, 'YYYY-MM-DD').startOf('day')
                   : moment().endOf('month').format('YYYY-MM-DD')
    };
}

Then in your routes:

var {startDate, endDate} = getDates(req);

Note that this is assuming you're using a vaguely up-to-date Node, which has support for concise object properties and destructuring assignment.

Related