cache-storage
Version:
[ABANDONED] Advanced cache storage for node js
117 lines (97 loc) • 3.26 kB
JavaScript
// Generated by CoffeeScript 1.6.3
(function() {
var Cache, FileStorage, Storage, fs, path,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Storage = require('./Storage');
Cache = require('../../Cache');
fs = null;
path = null;
FileStorage = (function(_super) {
__extends(FileStorage, _super);
FileStorage.prototype.directory = null;
FileStorage.prototype.allData = null;
FileStorage.prototype.data = null;
FileStorage.prototype.meta = null;
function FileStorage(directory) {
this.directory = directory;
if (typeof window !== 'undefined') {
throw new Error('FileStorage: Can not use this storage in browser');
}
fs = require('fs');
path = require('path');
this.directory = path.resolve(this.directory);
if (!Cache.getFs().existsSync(this.directory)) {
throw new Error('FileStorage: directory ' + this.directory + ' does not exists');
}
if (!Cache.getFs().statSync(this.directory).isDirectory()) {
throw new Error('FileStorage: path ' + this.directory + ' must be directory');
}
}
FileStorage.prototype.getFileName = function() {
return this.directory + '/__' + this.cache.namespace + '.json';
};
FileStorage.prototype.loadData = function(fn) {
var file,
_this = this;
if (this.allData === null) {
file = this.getFileName();
return Cache.getFs().exists(file, function(exists) {
if (exists) {
return Cache.getFs().readFile(file, {
encoding: 'utf8'
}, function(err, data) {
if (err) {
return fn(err, null);
} else {
_this.allData = JSON.parse(data);
return fn(null, _this.allData);
}
});
} else {
_this.allData = {
data: {},
meta: {}
};
return fn(null, _this.allData);
}
});
} else {
return fn(null, this.allData);
}
};
FileStorage.prototype.getData = function(fn) {
return this.loadData(function(err, data) {
return fn(err, data.data);
});
};
FileStorage.prototype.getMeta = function(fn) {
return this.loadData(function(err, data) {
return fn(err, data.meta);
});
};
FileStorage.prototype.writeData = function(data, meta, fn) {
var file;
this.data = data;
this.meta = meta;
this.allData = {
data: this.data,
meta: this.meta
};
file = this.getFileName();
Cache.getFs().writeFile(file, JSON.stringify({
data: this.data,
meta: this.meta
}), function(err) {
if (err) {
return fn(err);
} else {
return fn(null);
}
});
return this;
};
return FileStorage;
})(Storage);
module.exports = FileStorage;
}).call(this);