2018-02-16 15:52:44 +01:00
|
|
|
const memcached = require('memcached');
|
|
|
|
const winston = require('winston');
|
|
|
|
|
|
|
|
class MemcachedDocumentStore {
|
|
|
|
|
|
|
|
// Create a new store with options
|
|
|
|
constructor(options) {
|
|
|
|
this.expire = options.expire;
|
|
|
|
|
|
|
|
const host = options.host || '127.0.0.1';
|
|
|
|
const port = options.port || 11211;
|
|
|
|
const url = `${host}:${port}`;
|
|
|
|
this.connect(url);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a connection
|
|
|
|
connect(url) {
|
|
|
|
this.client = new memcached(url);
|
|
|
|
|
|
|
|
winston.info(`connecting to memcached on ${url}`);
|
|
|
|
|
|
|
|
this.client.on('failure', function(error) {
|
|
|
|
winston.info('error connecting to memcached', {error});
|
|
|
|
});
|
2012-01-17 20:43:33 +01:00
|
|
|
}
|
2018-02-16 15:52:44 +01:00
|
|
|
|
|
|
|
// Save file in a key
|
|
|
|
set(key, data, callback, skipExpire) {
|
2020-10-06 07:36:46 +02:00
|
|
|
this.client.set(key, data, skipExpire ? 0 : this.expire || 0, (error) => {
|
2018-02-16 15:52:44 +01:00
|
|
|
callback(!error);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get a file from a key
|
|
|
|
get(key, callback, skipExpire) {
|
|
|
|
this.client.get(key, (error, data) => {
|
2020-10-06 07:36:46 +02:00
|
|
|
const value = error ? false : data;
|
|
|
|
|
|
|
|
callback(value);
|
2018-02-16 15:52:44 +01:00
|
|
|
|
|
|
|
// Update the key so that the expiration is pushed forward
|
2020-10-06 07:36:46 +02:00
|
|
|
if (value && !skipExpire) {
|
2018-02-16 15:52:44 +01:00
|
|
|
this.set(key, data, (updateSucceeded) => {
|
|
|
|
if (!updateSucceeded) {
|
|
|
|
winston.error('failed to update expiration on GET', {key});
|
|
|
|
}
|
|
|
|
}, skipExpire);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2012-01-17 20:43:33 +01:00
|
|
|
|
|
|
|
module.exports = MemcachedDocumentStore;
|