I have a node application with many entry points. All entry points need to fetch a game server, based on a request parameter. If the server does not exist, I want to show the user an error message, and end the request.
function getGameServer(gametype, httpResponse) {
if (gameServers[gametype])
return gameServers[gametype];
else
httpResponse.end("Unknown game type '"+gametype+"'");
}
....
app.get('/:gametype/beginner', function(req,res) {
var gameServer = getGameServer(req.params.gametype, res);
console.log(gameServer.beginner_properties);
...
});
app.get('/:gametype/advanced', function(req,res) {
var gameServer = getGameServer(req.params.gametype, res);
console.log(gameServer.advanced_properties);
...
});
The problem is, if the function getGameServer doesn't find a game server, it does not stop after the "end" statement, but returns (with a null value), and so I get a node exception in the "gameServer.beginner_properties" or "gameServer.advanced_properties".
Of course I can check the return value in each ".get" function, however, there are many such functions and it is tedious to check the value in each one.
Is there a way to just end the request from within the getGameServer function?
I would make getGameServer a middleware:
function getGameServer(req, res, next) {
var gametype = req.params.gametype;
res.locals.gameserver = gameServers[gametype];
if (! res.locals.gameserver)
return res.end('Unknown game type "' + gametype + '"'); // end the request
next(); // this will call the next-in-line handler, which is your route handler below
}
app.get('/:gametype/beginner', getGameServer, function(req, res) {
console.log('server', res.locals.gameserver);
...
});
app.get('/:gametype/advanced', getGameServer, function(req, res) {
...
});
getGameServer basically acts as a filter: it ends the request if the game type isn't known, otherwise it will let the request pass so it will get handled by your routes.
You can refactor getGameServer to pass it a callback, and only call it if the server exists.
function getGameServer(gametype, httpResponse, callback) {
if (gameServers[gametype])
callback(httpResponse, gameServers[gametype]);
else
httpResponse.end("Unknown game type '"+gametype+"'");
}
....
app.get('/:gametype/beginner', function(req,res) {
getGameServer(req.params.gametype, res, function(res, gameServer) {
console.log(gameServer.beginner_properties);
});
...
});