Created
September 5, 2012 18:39
-
-
Save garrettwilkin/3642279 to your computer and use it in GitHub Desktop.
What the scope?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
I want to use a function so that i dont have to write the same logic over and over again in my calls to the find function on my MongoDb collections. | |
Here's the function I want, but notice that it contains 'self.res'. That's cause i just ripped it out of my find(...) call (below). Previously, when this was just an annoymous function, self.res is the HTTP response that we're building. | |
So how to i access self.res in my callback, if I use a named function, instead of an anonymous function in my find? | |
function findHandler(err, docs) { | |
if (!err) { | |
// Return Success & JSON Content-type | |
var length = docs.length; | |
writeMeta(self.res,200,url,length); | |
// Process results from Mongo | |
docs.forEach(function(e,i,a) { | |
//console.log(e,i,a); | |
self.res.write(JSON.stringify(e)+'\n'); | |
}); | |
self.res.end('\n'); | |
} else { | |
getHandlerError(self.res,url); | |
} | |
} | |
Flatiron route for my /force API endpoint: | |
app.router.get('/force',function() { | |
// Setup | |
var self = this; | |
var method = 'GET'; | |
var url = '/force'; | |
var body = self.req.body; | |
// Create metrics data. | |
var shlock = new Shlock('api', method, url); | |
shlock.body = body; | |
console.log(url,method,shlock); | |
// Check for query string | |
var query = self.req.query; | |
if (!isQueryValid(query)) { | |
writeMeta(self.res,400,url,0); | |
self.res.end('\n'); | |
} else { | |
// Handle count=true | |
if (query.hasOwnProperty('count') && | |
query.count === 'true') { | |
var only = getFindCriteria('force',query); | |
force.count(only,function(err,docs) { | |
writeMeta(self.res,200,url,docs); | |
self.res.end('\n'); | |
}); | |
} else { | |
// Handle paging | |
if (query.hasOwnProperty('page')) { | |
var only = getFindCriteria('force',query); | |
var fields = getFindFields('force',query); | |
force.find(only,fields,function(err,docs) { | |
var length = docs.length; | |
writeMeta(self.res,200,url,length); | |
// Process results from Mongo | |
docs.forEach(function(e,i,a) { | |
//console.log(e,i,a); | |
self.res.write(JSON.stringify(e)+'\n'); | |
}); | |
self.res.end('\n'); | |
}).skip(PAGE_SIZE*query.page) | |
.limit(PAGE_SIZE); | |
} else { | |
// Query Mongo | |
var only = getFindCriteria('force',query); | |
var fields = getFindFields('force',query); | |
force.find(only,fields,findHandler); | |
} | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment