The general way to approach refactoring is to identify what's different in your code and extract that to be a dynamic part that is passed into a function that contains the common code.
For instance, the two things that are different here are the path on which the requests happen
'/companies' vs '/companies/:id'
And the related path that gets passed to http.get
'/companies' vs '/companies/' + req.params.id
You can extract these and pass them into a function that will assign a handler for you.
Here's a generic approach:
// props contains the route and
// a function that extracts the path from the request
function setupGet(router, props) {
router.get('/' + props.route, function(req, res, next) {
http.get({
host: 'http://api.com',
path: props.getPath(req)
}, function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
});
res.render('company', {
data: body
});
});
}
And then call it with the two options:
setupGet(router, {
route: 'companies',
getPath: function(req) {
return 'companies';
}
});
setupGet(router, {
route: 'companies/:id',
getPath: function(req) {
return 'companies' + req.params.id;
}
});
The benefit here is that you can use any combination of routes and paths as well as use other req
properties to determine the path.
Another thing you need to realize is that your res.render
call will happen before you do body += d
, because the former happens synchronously right after the call to http.get
and the latter happens asynchronously (sometime later).
You probably want to put the render
method in the callback itself.
// props contains the route and
// a function that extracts the path from the request
function setupGet(router, props) {
router.get('/' + props.route, function(req, res, next) {
http.get({
host: 'http://api.com',
path: props.getPath(req)
}, function(response) {
var body = '';
response.on('data', function(d) {
body += d;
// probably want to render here
res.render('company', {
data: body
});
});
});
});
}