Added count function

This commit is contained in:
Dallon Feldner
2012-10-09 11:32:56 -07:00
parent 855cead6d4
commit 618c76a4cf
3 changed files with 73 additions and 0 deletions

View File

@@ -269,6 +269,42 @@ Store.prototype.insert = function (object, fn) {
});
};
/**
* Find the number of objects in the store that match the given query.
*
* Example:
*
* db
* .connect({host: 'localhost', port: 27015, name: 'test'})
* .createStore('testing-store')
* .count({foo: 'bar'}, fn)
*
* @param {Object} query
* @param {Function} callback(err, num)
*/
Store.prototype.count = function(query, fn) {
var store = this;
if (typeof query == 'function') {
fn = query;
query = {};
} else {
query && this.scrubQuery(query);
}
var fields = stripFields(query)
, options = stripOptions(query);
collection(this, function (err, col) {
if (err) return fn(err);
col.find(query, fields, options).count(function(err, count) {
if (err) return fn(err);
fn(null, count);
});
});
};
/**
* Find all objects in the store that match the given query.
*

View File

@@ -169,6 +169,12 @@ Collection.prototype.handle = function (ctx) {
// set id one wasnt provided in the query
ctx.query.id = ctx.query.id || this.parseId(ctx) || (ctx.body && ctx.body.id);
if (ctx.req.method == "GET" && ctx.query.id === 'count') {
delete ctx.query.id;
this.count(ctx, ctx.done);
return;
}
switch(ctx.req.method) {
case 'GET':
this.find(ctx, ctx.done);
@@ -200,6 +206,25 @@ Collection.prototype.parseId = function(ctx) {
if(ctx.url && ctx.url !== '/') return ctx.url.split('/')[1];
};
Collection.prototype.count = function(ctx, fn) {
if (ctx.session.isRoot) {
var collection = this
, store = this.store
, sanitizedQuery = this.sanitizeQuery(ctx.query || {});
store.count(sanitizedQuery, function (err, result) {
if (err) return fn(err);
fn(null, {count: result});
});
} else {
fn({
message: "Must be root to count",
statusCode: 403
});
}
};
/**
* Find all the objects in a collection that match the given
* query. Then execute its get script using each object.

View File

@@ -68,6 +68,18 @@ describe('store', function(){
});
});
});
describe('.count({}, fn)', function() {
it('should count the results', function(done) {
store.insert([{i:1},{i:2},{i:33333},{i:4},{i:5},{i:6},{i:7},{i:8},{i:9}], function () {
store.count({}, function (err, result) {
expect(result).to.exist;
expect(result).to.equal(9);
done(err);
});
});
});
});
});
describe('.identify(object)', function() {