After cleaning up & some refactoring, one module of my code became like below. However, I'm feeling like there's still some unnecessary redundancy, and it can be improved further and look neater.
But I can't come up with exactly how to do it.
'use strict';
// === showing the execution context ==============
const express = require('express');
const router = express.Router();
const moment = require("moment");
const momentDurationSetup = require("moment-duration-format");
const DB = require('./DBOperator');
const _ = require('lodash');
const Promise = require("bluebird");
const request = require('superagent-bluebird-promise');
const utils = require('../utils');
// ========== main concern area ===============
function realTime(queryFunction, payload, req, res, next) {
queryFunction((err, results) => {
if (err) {
console.log(err);
next();
} else {
res.json({data: _.get(results[0].rows[0], payload, -1)});
}
});
}
router.get('/online-buyer-count', utils.mcache(15), (req, res, next) => {
realTime(DB.onlinebuyerNumQuery, 'onlinebuyerNum', req, res, next);
});
router.get('/offline-buyer-count', utils.mcache(15), (req, res, next) => {
realTime(DB.offlinebuyerNumQuery, 'offlinebuyerNum', req, res, next);
});
router.get('/online-seller-count', utils.mcache(15), (req, res, next) => {
realTime(DB.onlinesellerNumQuery, 'onlinesellerNum', req, res, next);
});
router.get('/offline-seller-count', utils.mcache(15), (req, res, next) => {
realTime(DB.offlinesellerNumQuery, 'offlinesellerNum', req, res, next);
});
/ ===========================
module.exports = router;