Permalink
Browse files

Add purgeDB method. (DANGEROUS!)

  • Loading branch information...
maritz committed Dec 19, 2011
1 parent cbe4253 commit 5bc4c25c19a5cb2585e30987298df17c11243b7a
Showing with 66 additions and 0 deletions.
  1. +35 −0 lib/nohm.js
  2. +31 −0 test/featureTests.js
View
@@ -1,4 +1,5 @@
var h = require(__dirname + '/helpers');
+var async = require('async');
/**
* The Nohm object used for some general configuration and model creation.
@@ -250,6 +251,40 @@ Nohm.prototype.init = function (name, options) {
this.__loaded = false;
};
+/**
+ * DO NOT USE THIS UNLESS YOU ARE ABSOLUTELY SURE ABOUT IT!
+ *
+ * Deletes any keys from the db that start with nohm prefixes.
+ *
+ * DO NOT USE THIS UNLESS YOU ARE ABSOLUTELY SURE ABOUT IT!
+ *
+ * @param {Object} [redis] You can specify the redis client to use. Default: Nohm.client
+ * @param {Function} [callback] Called after all keys are deleted.
+ */
+Nohm.purgeDb = function (redis, callback) {
+ callback = h.getCallback(arguments);
+ redis = typeof(redis) !== 'function' || Nohm.client;
+ var delKeys = function (prefix, next) {
+ redis.keys(prefix+'*', function (err, keys) {
+ if (err || keys.length === 0) {
+ next(err);
+ } else {
+ keys.push(next);
+ redis.del.apply(redis, keys);
+ }
+ });
+ };
+ var deletes = [];
+
+ Object.keys(Nohm.prefix).forEach(function (key) {
+ deletes.push(async.apply(delKeys, Nohm.prefix[key]));
+ });
+
+ async.series(deletes, function (err) {
+ callback(err);
+ });
+};
+
var moduleNames = ['properties', 'retrieve', 'validation', 'store', 'relations', 'connectMiddleware'],
modules = {};
View
@@ -834,3 +834,34 @@ exports.factory = function (t) {
});
t.ok(user2, 'Using the factory with an id and callback returned false');
};
+
+exports.purgeDB = function (t) {
+ var expected = 1;
+ var countKeys = function (prefix, callback) {
+ redis.keys(prefix+'*', function (err, orig_num) {
+ callback(err, orig_num.length);
+ });
+ };
+
+ var tests = [];
+ Object.keys(nohm.prefix).forEach(function (key) {
+ expected += 2;
+ tests.push(async.apply(countKeys, nohm.prefix[key]));
+ });
+
+ async.series(tests, function (err, num_arr) {
+ t.ok(!err, 'Unexpected redis error');
+ var count = num_arr.reduce(function (num, add) { return num + add; }, 0);
+ t.ok(count > 0, 'Database did not have any keys');
+ nohm.purgeDb(function (err) {
+ t.ok(!err, 'Unexpected redis error');
+ async.series(tests, function (err, num_arr) {
+ t.ok(!err, 'Unexpected redis error');
+ var count = num_arr.reduce(function (num, add) { return num + add; }, 0);
+ t.same(count, 0, 'Database did have keys left after purging.');
+ t.done();
+ });
+ });
+ });
+};
+

0 comments on commit 5bc4c25

Please sign in to comment.