I think I am repeating the same piece of code each time. Is there any way to shorten this code so that I do not have to rewrite it?
router.get('/reports', async (req, res) => {
let filters = {};
if (req.query.y) filters['end_year'] = req.query.y.split(',');
if (req.query.t) filters['topic'] = req.query.t.split(',');
if (req.query.s) filters['sector'] = req.query.s.split(',');
if (req.query.r) filters['region'] = req.query.r.split(',');
if (req.query.src) filters['source'] = req.query.src.split(',');
const reports = await Report.find(filters);
});
CodePudding user response:
What about using a mapping object, and iterate through req
? Something like:
const filterMap = {
y: `end_year`, t: `topic`, s: `sector`,
r: `region`, src: `source` };
Object.keys(req.query).forEach(k => {
if (filterMap[k]) {
filters[filterMap[k]] = req.query[k].split(`,`));
}
});
CodePudding user response:
Another option, is create a simple sub function.
const query = {
y: '2022',
t: 'C ',
s: 'Accounts',
r: 'South West',
src: 'Bloomberg'
};
{
const filters = {};
const set=(s,d)=>filters[d]=query[s];
set('y', 'end_year');
set('t', 'topic');
set('s', 'sector');
set('r', 'region');
set('src', 'source');
console.log(filters);
}