1
0
Fork 0
mirror of https://github.com/seejohnrun/haste-server.git synced 2024-11-01 11:31:22 +00:00
haste-server/lib/redis_document_store.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2011-11-19 00:52:18 +00:00
var redis = require('redis');
var winston = require('winston');
var hashlib = require('hashlib');
2011-11-22 03:03:50 +00:00
// For storing in redis
// options[type] = redis
// options[host] - The host to connect to (default localhost)
// options[port] - The port to connect to (default 5379)
// options[db] - The db to use (default 0)
// options[expire] - The time to live for each key set (default never)
2011-11-19 00:52:18 +00:00
var RedisDocumentStore = function(options) {
2011-11-22 03:03:50 +00:00
this.expire = options.expire;
2011-11-19 00:52:18 +00:00
if (!RedisDocumentStore.client) {
2011-11-19 00:59:41 +00:00
RedisDocumentStore.connect(options);
2011-11-19 00:52:18 +00:00
}
};
2011-11-19 00:59:41 +00:00
// Create a connection according to config
RedisDocumentStore.connect = function(options) {
var host = options.host || '127.0.0.1';
var port = options.port || 6379;
var index = options.db || 0;
RedisDocumentStore.client = redis.createClient(port, host);
RedisDocumentStore.client.select(index, function(err, reply) {
if (err) {
winston.error('error connecting to redis index ' + index, { error: error.message });
process.exit(1);
}
else {
winston.info('connected to redis on ' + host + ':' + port + '/' + index);
}
});
};
2011-11-19 00:52:18 +00:00
// Save file in a key
RedisDocumentStore.prototype.set = function(key, data, callback) {
2011-11-22 03:03:50 +00:00
var _this = this;
2011-11-19 00:52:18 +00:00
RedisDocumentStore.client.set(key, data, function(err, reply) {
2011-11-22 03:03:50 +00:00
if (err) {
callback(false);
}
else {
_this.setExpiration(key);
callback(true);
}
2011-11-19 00:52:18 +00:00
});
};
2011-11-22 03:03:50 +00:00
// Expire a key in expire time if set
RedisDocumentStore.prototype.setExpiration = function(key) {
if (this.expire) {
RedisDocumentStore.client.expire(key, this.expire, function(err, reply) {
if (err || !reply) {
winston.error('failed to set expiry on key: ' + key);
}
});
}
};
2011-11-19 00:52:18 +00:00
// Get a file from a key
RedisDocumentStore.prototype.get = function(key, callback) {
RedisDocumentStore.client.get(key, function(err, reply) {
callback(err ? false : reply);
});
};
module.exports = RedisDocumentStore;