91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
var FILE_SYSTEM_NAME = require('../constants.js').FILE_SYSTEM_NAME;
|
|
// NOTE: prefer setImmediate to nextTick for proper recursion yielding.
|
|
// see https://github.com/js-platform/filer/pull/24
|
|
var asyncCallback = require('../../lib/async.js').setImmediate;
|
|
|
|
/**
|
|
* Make shared in-memory DBs possible when using the same name.
|
|
*/
|
|
var createDB = (function() {
|
|
var pool = {};
|
|
return function getOrCreate(name) {
|
|
if(!pool.hasOwnProperty(name)) {
|
|
pool[name] = {};
|
|
}
|
|
return pool[name];
|
|
};
|
|
}());
|
|
|
|
function MemoryContext(db, readOnly) {
|
|
this.readOnly = readOnly;
|
|
this.objectStore = db;
|
|
}
|
|
|
|
MemoryContext.prototype.clear = function(callback) {
|
|
if(this.readOnly) {
|
|
asyncCallback(function() {
|
|
callback("[MemoryContext] Error: write operation on read only context");
|
|
});
|
|
return;
|
|
}
|
|
var objectStore = this.objectStore;
|
|
Object.keys(objectStore).forEach(function(key){
|
|
delete objectStore[key];
|
|
});
|
|
asyncCallback(callback);
|
|
};
|
|
|
|
// Memory context doesn't care about differences between Object and Buffer
|
|
MemoryContext.prototype.getObject =
|
|
MemoryContext.prototype.getBuffer =
|
|
function(key, callback) {
|
|
var that = this;
|
|
asyncCallback(function() {
|
|
callback(null, that.objectStore[key]);
|
|
});
|
|
};
|
|
MemoryContext.prototype.putObject =
|
|
MemoryContext.prototype.putBuffer =
|
|
function(key, value, callback) {
|
|
if(this.readOnly) {
|
|
asyncCallback(function() {
|
|
callback("[MemoryContext] Error: write operation on read only context");
|
|
});
|
|
return;
|
|
}
|
|
this.objectStore[key] = value;
|
|
asyncCallback(callback);
|
|
};
|
|
|
|
MemoryContext.prototype.delete = function(key, callback) {
|
|
if(this.readOnly) {
|
|
asyncCallback(function() {
|
|
callback("[MemoryContext] Error: write operation on read only context");
|
|
});
|
|
return;
|
|
}
|
|
delete this.objectStore[key];
|
|
asyncCallback(callback);
|
|
};
|
|
|
|
|
|
function Memory(name) {
|
|
this.name = name || FILE_SYSTEM_NAME;
|
|
}
|
|
Memory.isSupported = function() {
|
|
return true;
|
|
};
|
|
|
|
Memory.prototype.open = function(callback) {
|
|
this.db = createDB(this.name);
|
|
asyncCallback(callback);
|
|
};
|
|
Memory.prototype.getReadOnlyContext = function() {
|
|
return new MemoryContext(this.db, true);
|
|
};
|
|
Memory.prototype.getReadWriteContext = function() {
|
|
return new MemoryContext(this.db, false);
|
|
};
|
|
|
|
module.exports = Memory;
|