Issue
I’m making a poll app, and one of my routes is a GET request to get all the polls.
All i want to do is pass the polls to my dashboard view, and if there are no polls I want to pass the error to the dashboard view also.
I think my current implementation is wrong because if there are no polls the dashboard view receives an empty array not the errors.
I was curious what the best approach would be in this situation.
Thanks
router.get('/dashboard', isAuth, async (req, res) => {
try {
const polls = await Poll.find().populate('user', ['name', 'id']);
res.render('dashboard', {
polls
});
} catch(err) {
res.status(400);
res.render('dashboard', {
error: 'Could not find any polls'
});
}
});
Solution
You can throw error if polls
is falsy/empty. Like this this:
const getType = element => Object.prototype.toString.call(element);
// Put this function in a helper file and use it throughout the source code
const isEmpty = element => {
if (
// undefined
typeof element === 'undefined' ||
// string
(typeof element === 'string' && element.trim().length == 0) ||
// null
getType(element) === '[object Null]' ||
// object
(getType(element) === '[object Object]' && !Object.keys(element).length) ||
// array
(getType(element) === '[object Array]' && !element.length)
) {
return true;
}
return false;
}
router.get('/dashboard', isAuth, async (req, res) => {
try {
const polls = await Poll.find().populate('user', ['name', 'id']);
if (isEmpty(polls)) {
throw new Error("Could not find any polls");
}
res.render('dashboard', {
polls
});
} catch (err) {
res.status(400);
res.render('dashboard', {
error: 'Could not find any polls'
});
}
});