Michael Vasilevsky
asked on
How to Direct a Route Depending on Criteria in Node.js?
This is a node.js application. I have a route like:
What is the best way to do this?
getDevices is something like:
So I want the "/" route to render "devices" if the user has devices, "models" if not. I tried the below but it seems like totally the wrong approach.
Can anyone point me in the right direction?
router.get('/', ...));
that I want to render
deviceController.getDevices
if
const devices = await Device.find({ owner: req.user._id });
is truthy, and
modelController.getModels
if not. What is the best way to do this?
getDevices is something like:
exports.getDevices = async (req, res) => {
...
res.render('devices', { title: 'My Devices', devices });
};
getModels is something like:exports.getModels = async (req, res) => {
...
res.render('models', { title: 'Models', models, page, pages, count });
};
So I want the "/" route to render "devices" if the user has devices, "models" if not. I tried the below but it seems like totally the wrong approach.
router.post('/login', authController.login, deviceController.hasDevice);
exports.login = (req, res, next) => {
passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: 'Failed Login'
});
next();
};
exports.hasDevice = async (req, res) => {
const devices = await Device.find({ owner: req.user._id });
if (!devices.length) {
res.render('store', { title: 'Store' });
} else {
res.render('devices', { title: 'My Devices', devices });
}
};
Can anyone point me in the right direction?
ASKER
Not exactly sure what you mean Julian. Could you provide some mock code?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
aah okay so it would look something like:
I'm not able to test until this evening here (about 8 hours from now).
router.get('/', someController.findRoute));
exports.findRoute= async (req, res) => {
const devices = await Device.find({ owner: req.user._id });
if (!devices.length) {
res.redirect('/models');
} else {
res.redirect('/devices');
}
};
I'm not able to test until this evening here (about 8 hours from now).
Precisely.
In my view this is a better design as it keeps your functionality neatly compartmentalised - easy to understand what is happening. /Devices shows devices /Models shows models and you are creating one or other default when accessing / based on what is available - but you can still get to either by its own route.
In my view this is a better design as it keeps your functionality neatly compartmentalised - easy to understand what is happening. /Devices shows devices /Models shows models and you are creating one or other default when accessing / based on what is available - but you can still get to either by its own route.
ASKER
Thanks for the help Julian!
You are welcome
/ => Devices exists
no redirect -> models