Permalink
Browse files

All, all instances

  • Loading branch information...
1 parent 65a364d commit 872f81f882de8ea79b1d700e84e1d46475af6d1e Anatoliy Chakkaev committed Nov 22, 2010
Showing with 76 additions and 18 deletions.
  1. +45 −0 lib/orm.js
  2. +13 −0 test/find_all.js
  3. +18 −18 test/orm.js
View
@@ -106,6 +106,51 @@ function add_persistence_methods(Model, model_name, namespace) {
});
};
+ Model.all = function (options, callback) {
+ if (arguments.length == 1) {
+ callback = options;
+ options = {};
+ }
+ var page = options.page || 0,
+ shape_size = options.shape_size || 2;
+
+ redis.get('ids:' + model_name.toLowerCase(), function (err, value) {
+ value = value.toString();
+ var mask = value.slice(0, -shape_size);
+ for (var i = 0; i < shape_size; i++) {
+ mask += '?';
+ }
+ redis.keys(model_name.toLowerCase() + ':' + mask, function (error, ids) {
+ for (var i in ids) ids[i] = parseInt(ids[i].toString().split(':')[1], 10);
+ callback.call(null, ids);
+ });
+ });
+ };
+
+ Model.all_instances = function (options, callback) {
+ if (arguments.length == 1) {
+ callback = options;
+ options = {};
+ }
+ var result = [];
+ Model.all(function (ids) {
+ var count = ids.length;
+ if (count > 0) {
+ for (var i in ids) {
+ Model.find(ids[i], function () {
+ result.push(this);
+ count -= 1;
+ if (count == 0) {
+ callback(result);
+ }
+ });
+ }
+ } else {
+ callback([]);
+ }
+ });
+ };
+
Model.prototype.update_attribute = function accessor(attr, value, callback) {
var self = this;
View
@@ -0,0 +1,13 @@
+var models = {};
+models.Player = function Player() { };
+models.Player.attributes = {
+ game_id: 'int'
+};
+
+require('../lib/orm.js').mix_persistence_methods(models);
+exports['should find all records'] = function (test) {
+ models.Player.all(function (data) {
+ test.ok(data);
+ test.done();
+ });
+};
View
@@ -168,21 +168,21 @@ context('instance methods', function () {
});
});
-// it('should work really fast', function (test) {
-// test.expect(1);
-//
-// var n = 0;
-// for (var i = 0; i < 10000; i++) {
-// (function (i) {
-// ++n;
-// models.Player.create(function (player_id) {
-// --n;
-// if (n === 0) {
-// test.ok(true);
-// models.Player.connection.flushdb();
-// test.done();
-// }
-// });
-// })(i);
-// }
-// });
+it('should work really fast', function (test) {
+ test.expect(1);
+
+ var n = 0;
+ for (var i = 0; i < 1000; i++) {
+ (function (i) {
+ ++n;
+ models.Player.create(function (player_id) {
+ --n;
+ if (n === 0) {
+ test.ok(true);
+ //models.Player.connection.flushdb();
+ test.done();
+ }
+ });
+ })(i);
+ }
+});

0 comments on commit 872f81f

Please sign in to comment.