Skip to content

Instantly share code, notes, and snippets.

@oren
Created Feb 16, 2013
Embed
What would you like to do?
// The server's main routes function
//
// Supports the following end-points:
// POST /push
// POST /register
// POST /register.php
// GET /health
// GET /health.txt
function router(config, req, res) {
if (req.url == '/push') {
if(req.method.toLowerCase() == 'post') {
pusher(config, req, res);
} else {
res.statusCode = 405;
res.end();
}
} else if (req.url == '/register') {
if(req.method.toLowerCase() == 'post') {
register(config, req, res);
} else {
res.statusCode = 405;
res.end();
}
} else if (req.url == '/register.php') {
if(req.method.toLowerCase() == 'post') {
registerLegacy(config, req, res);
} else {
res.statusCode = 405;
res.end();
}
} else if (req.url == '/health') {
if(req.method.toLowerCase() == 'get') {
info = health(req.connections);
res.end(JSON.stringify(info));
} else {
res.statusCode = 405;
res.end();
}
} else if (req.url == '/health.txt') {
if(req.method.toLowerCase() == 'get') {
checkHealth(req, res);
} else {
res.statusCode = 405;
res.end();
}
} else {
res.statusCode = 404;
res.end();
};
};
// after extracting 5 functions
// complexity was reduced from 11 to 6
function router(config, req, res) {
if (req.url == '/push') {
pushRoute();
} else if (req.url == '/register') {
registerRoute();
} else if (req.url == '/register.php') {
registerPhpRoute();
} else if (req.url == '/health') {
healthRoute();
} else if (req.url == '/health.txt') {
healthTxtRoute();
} else {
res.statusCode = 404;
res.end();
}
function pushRoute() {
if(req.method.toLowerCase() == 'post') {
pusher(config, req, res);
} else {
res.statusCode = 405;
res.end();
}
}
function registerRoute() {
if(req.method.toLowerCase() == 'post') {
register(config, req, res);
} else {
res.statusCode = 405;
res.end();
}
}
function registerPhpRoute() {
if(req.method.toLowerCase() == 'post') {
registerLegacy(config, req, res);
} else {
res.statusCode = 405;
res.end();
}
}
function healthRoute() {
if(req.method.toLowerCase() == 'get') {
info = health(req.connections);
res.end(JSON.stringify(info));
} else {
res.statusCode = 405;
res.end();
}
}
function healthTxtRoute() {
if(req.method.toLowerCase() == 'get') {
checkHealth(req, res);
} else {
res.statusCode = 405;
res.end();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment