This is my app.all. Basically, I'm calling a fetchBuildings function based on the building ID/Hash, then setting title, description, and image based on the response:
app.all('/:id', function (req, res) {
const hash = req.params.id
const obj = {}
if (hash === 'undefined') {
obj.title = 'iStaging LiveTour'
obj.description = ''
obj.image = 'https://raw.githubusercontent.com/alexcheninfo/vue-tmux-example/master/app/istaging.jpg'
return
}
fetchBuildingsByHash(hash).then(({title, description, image, isBasicPlan}) => {
if (isBasicPlan) {
obj.title = 'iStaging LiveTour'
obj.description = ''
obj.image = 'https://raw.githubusercontent.com/alexcheninfo/vue-tmux-example/master/app/istaging.jpg'
} else {
obj.title = title || 'iStaging LiveTour'
obj.description = description || ''
obj.image = image || 'https://raw.githubusercontent.com/alexcheninfo/vue-tmux-example/master/app/istaging.jpg'
}
res.render('index.ejs', obj)
}).catch((err) => {
const obj = {
title: 'notFound'
}
res.render('404.ejs', obj)
})
});
Sometimes hash is 'undefined' so I want to stop the code when that happens.
I'm just using return here, but I wonder if this is the conventional way of doing it. Is there another more 'proper' way?
You should always either return a response, or pass the request along the middleware chain. If you just return, the request will get "stuck": the client will keep on waiting for a response that never comes, and eventually it will time out.
Let's assume that passing an hash of undefined is considered invalid. You could return a 400 ("Bad Request") response in that case:
if (hash === 'undefined') {
return res.sendStatus(400);
}
If you want to pass the request along, which will likely result in a 404 ("Not Found") response being returned by Express:
app.all('/:id', function (req, res, next) {
const hash = req.params.id
const obj = {}
if (hash === 'undefined') {
return next();
}
...
})
Or explicitly pass an error, resulting in a 500 ("Internal Server Error") response returned by Express:
if (hash === 'undefined') {
return next(Error('invalid hash'));
}