update File to write wallets to different files

the walletId is the filename
This commit is contained in:
Ryan X. Charles 2014-04-16 17:37:32 -03:00
commit 5f8deb7d0b
2 changed files with 51 additions and 43 deletions

View file

@ -6,47 +6,54 @@ function Storage(opts) {
opts = opts || {};
this.data = {};
this.filename = opts.filename;
}
Storage.prototype.load = function(callback) {
if (!this.filename)
throw new Error('No filename');
fs.readFile(this.filename, function(err, data) {
Storage.prototype.load = function(walletId, callback) {
fs.readFile(walletId, function(err, data) {
if (err) return callback(err);
try {
this.data = JSON.parse(data);
this.data[walletId] = JSON.parse(data);
} catch (err) {
return callback(err);
if (callback)
return callback(err);
}
return callback(null);
if (callback)
return callback(null);
});
};
Storage.prototype.save = function(callback) {
var data = JSON.stringify(this.data);
Storage.prototype.save = function(walletId, callback) {
var data = JSON.stringify(this.data[walletId]);
//TODO: update to use a queue to ensure that saves are made sequentially
fs.writeFile(this.filename, data, function(err) {
return callback(err);
fs.writeFile(walletId, data, function(err) {
if (callback)
return callback(err);
});
};
Storage.prototype._read = function(k) {
return this.data[k];
var split = k.split('::');
var walletId = split[0];
var key = split[1];
return this.data[walletId][key];
};
Storage.prototype._write = function(k, v, callback) {
this.data[k] = v;
this.save(callback);
var split = k.split('::');
var walletId = split[0];
var key = split[1];
if (!this.data[walletId])
this.data[walletId] = {};
this.data[walletId][key] = v;
this.save(walletId, callback);
};
// get value by key
Storage.prototype.getGlobal = function(k) {
return this.data[k];
return this._read(k);
};
// set value for key
@ -56,13 +63,17 @@ Storage.prototype.setGlobal = function(k, v, callback) {
// remove value for key
Storage.prototype.removeGlobal = function(k, callback) {
delete this.data[k];
this.save(callback);
var split = k.split('::');
var walletId = split[0];
var key = split[1];
delete this.data[walletId][key];
this.save(walletId, callback);
};
Storage.prototype._key = function(walletId, k) {
return walletId + '::' + k;
};
// get value by key
Storage.prototype.get = function(walletId, k) {
return this.getGlobal(this._key(walletId, k));