Skip to content

Instantly share code, notes, and snippets.

@mattpowell
Created February 18, 2013 09:02
Show Gist options
  • Save mattpowell/4976057 to your computer and use it in GitHub Desktop.
Save mattpowell/4976057 to your computer and use it in GitHub Desktop.
sqlitecache - A super basic layer on top of sqlite for caching certain types of requests. Works well as a replacement (especially in dev) for memcached when working w/ limited/throttled services (like Embed.ly or LinkedIn's API).
var Sqlite = require('sqlite3').verbose();
function SqliteCache( config ) {
config = config || {};
this.db = new Sqlite.Database( config.db || void(0)); // will create an in-memory store if path is undefined.
this.bucket = config.bucket || '';
this.duration = config.duration || 1000 * 60 * 5;//defaults to 5 minutes
//initialize table
this.db.run("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY ASC, expires INTEGER, result TEXT)");
//clean out old keys on startup
this.db.run('DELETE FROM cache WHERE expires <= ?', [ Date.now() ], function() {});
}
SqliteCache.prototype = {
get: function(key, callback) {
var self = this;
key = this.bucket + key;
//this.db.get('SELECT * FROM cache WHERE key = "?" AND expires >= ? LIMIT 1',[ key, Date.now()], function(err, row) {
this.db.get('SELECT * FROM cache WHERE key = "' + key + '" AND expires >= ' + Date.now() + ' LIMIT 1', function(err, row) {
var result = row && JSON.parse(row.result);
callback.call(self, err, result);
});
},
set: function(key, value, callback) {
var self = this,
expires = Date.now() + this.duration,
resultVal = JSON.stringify(value).replace(/'/g, '\'\'');
key = this.bucket + key;
//this.db.run('INSERT OR REPLACE INTO cache (key, expires, result) VALUES ("?", ?, "?")', [key, expires, resultVal], function(err) {
this.db.run("INSERT OR REPLACE INTO cache (key, expires, result) VALUES ('" + key + "', " + expires + ", '" + resultVal + "')", function(err) {
callback.call(self, err, value);
});
},
contains: function(key, callback) {
var self = this;
this.get(key, function(err, result) {
callback.call(self, err, !!result);
});
},
remove: function(key, callback) {
var self = this;
this.db.run('DELETE FROM cache WHERE key <= ?', [ key ], function(err, result) {
//TODO: not sure what result says. Could we pass that to the callback function?
callback.call(self, err, !err);
});
}
};
module.exports = SqliteCache;
{
"name": "sqlitecache",
"author": "Matt Powell",
"description": "tbd",
"main": "./index.js",
"version": "0.0.1"
}
@mattpowell
Copy link
Author

Now, you can run this: npm install https://gist.github.com/mattpowell/4976057/download

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment