copay/js/plugins/LocalStorage.js

80 lines
1.6 KiB
JavaScript
Raw Normal View History

2014-09-01 19:44:35 -07:00
'use strict';
var _ = require('lodash');
2014-09-01 19:44:35 -07:00
function LocalStorage() {
2014-09-30 11:28:02 -07:00
this.type = 'DB';
2014-09-01 19:44:35 -07:00
};
LocalStorage.prototype.init = function() {
};
LocalStorage.prototype.setCredentials = function(email, password, opts) {
2014-10-27 06:36:17 -07:00
this.email = email;
this.password = password;
};
2014-09-02 21:25:08 -07:00
LocalStorage.prototype.getItem = function(k,cb) {
2014-10-27 07:57:13 -07:00
return cb(null, localStorage.getItem(k));
2014-09-01 19:44:35 -07:00
};
2014-10-28 11:20:43 -07:00
/**
* Same as setItem, but fails if an item already exists
*/
LocalStorage.prototype.createItem = function(name, value, callback) {
if (localStorage.getItem(name)) {
return callback('EEXISTS');
}
return this.setItem(name, value, callback);
};
2014-09-02 21:25:08 -07:00
LocalStorage.prototype.setItem = function(k,v,cb) {
2014-09-01 19:44:35 -07:00
localStorage.setItem(k,v);
2014-09-02 21:25:08 -07:00
return cb();
2014-09-01 19:44:35 -07:00
};
2014-09-02 21:25:08 -07:00
LocalStorage.prototype.removeItem = function(k,cb) {
2014-09-01 19:44:35 -07:00
localStorage.removeItem(k);
2014-09-02 21:25:08 -07:00
return cb();
2014-09-01 19:44:35 -07:00
};
2014-09-02 21:25:08 -07:00
LocalStorage.prototype.clear = function(cb) {
2014-09-01 19:44:35 -07:00
localStorage.clear();
2014-09-02 21:25:08 -07:00
return cb();
2014-09-01 19:44:35 -07:00
};
2014-09-02 21:25:08 -07:00
LocalStorage.prototype.allKeys = function(cb) {
var l = localStorage.length;
var ret = [];
2014-09-01 19:44:35 -07:00
2014-09-02 21:25:08 -07:00
for(var i=0; i<l; i++)
ret.push(localStorage.key(i));
2014-09-01 19:44:35 -07:00
2014-10-27 07:57:13 -07:00
return cb(null, ret);
2014-09-01 19:44:35 -07:00
};
LocalStorage.prototype.getFirst = function(prefix, opts, cb) {
opts = opts || {};
var that = this;
this.allKeys(function(err, allKeys) {
var keys = _.filter(allKeys, function(k) {
if ((k === prefix) || k.indexOf(prefix) === 0) return true;
});
if (keys.length === 0)
return cb(new Error('not found'));
if (opts.onlyKey)
return cb(null, null, keys[0]);
that.getItem(keys[0], function(err, data) {
if (err) {
return cb(err);
}
return cb(null, data, keys[0]);
});
});
};
2014-09-01 19:44:35 -07:00
module.exports = LocalStorage;