2017-01-30 15:44:47 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
|
2017-01-30 16:31:28 +01:00
|
|
|
// Core
|
|
|
|
const util = require('util');
|
|
|
|
|
|
|
|
// Public node modules.
|
|
|
|
const _ = require('lodash');
|
|
|
|
const Redis = require('ioredis');
|
|
|
|
|
2017-01-30 15:44:47 +01:00
|
|
|
/**
|
|
|
|
* Redis hook
|
|
|
|
*/
|
|
|
|
|
|
|
|
module.exports = function () {
|
|
|
|
const hook = {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Default options
|
|
|
|
*/
|
|
|
|
|
2017-01-30 16:31:28 +01:00
|
|
|
defaults: {
|
|
|
|
port: 6379,
|
|
|
|
host: 'localhost',
|
|
|
|
family: 4,
|
|
|
|
db: 0
|
|
|
|
},
|
2017-01-30 15:44:47 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Initialize the hook
|
|
|
|
*/
|
|
|
|
|
|
|
|
initialize: cb => {
|
2017-01-30 16:31:28 +01:00
|
|
|
const connections = _.pickBy(strapi.config.connections, {connector: 'strapi-redis'});
|
|
|
|
|
|
|
|
const done = _.after(_.size(connections), () => {
|
|
|
|
cb();
|
|
|
|
});
|
|
|
|
|
|
|
|
// For each connection in the config register a new Knex connection.
|
|
|
|
_.forEach(connections, (connection, name) => {
|
|
|
|
// Apply defaults
|
|
|
|
_.defaults(connection.settings, strapi.hooks.redis.defaults);
|
|
|
|
|
|
|
|
try {
|
|
|
|
const redis = new Redis(connection.settings);
|
|
|
|
|
|
|
|
redis.on('error', (err) => {
|
|
|
|
cb(err);
|
|
|
|
|
|
|
|
return process.kill();
|
|
|
|
});
|
|
|
|
|
2017-02-01 17:17:06 +01:00
|
|
|
// Utils function.
|
|
|
|
// Behavior: Try to retrieve data from Redis, if null
|
|
|
|
// execute callback and set the value in Redis for this serial key.
|
|
|
|
redis.cache = async (serial, cb, type) => {
|
|
|
|
let cache = await redis.get(serial);
|
|
|
|
|
|
|
|
if (!cache) {
|
|
|
|
cache = await cb();
|
|
|
|
|
2017-02-03 11:55:31 +01:00
|
|
|
if (cache && _.get(connection, 'options.disabledCaching') !== true) {
|
2017-02-01 17:17:06 +01:00
|
|
|
redis.set(serial, cache);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (type) {
|
|
|
|
case 'int':
|
|
|
|
return parseInt(cache);
|
|
|
|
default:
|
|
|
|
return cache;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-01-30 16:31:28 +01:00
|
|
|
// Define as new connection.
|
|
|
|
strapi.connections[name] = redis;
|
|
|
|
|
|
|
|
// Expose global
|
|
|
|
if (_.get(connection, 'options.global') !== false) {
|
|
|
|
global[_.get(connection, 'options.globalName') || 'redis'] = redis;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (_.get(connection, 'options.debug') === true) {
|
|
|
|
redis.monitor((err, monitor) => {
|
|
|
|
// Entering monitoring mode.
|
|
|
|
monitor.on('monitor', (time, args) => {
|
|
|
|
console.log(time + ': ' + util.inspect(args));
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
done();
|
|
|
|
} catch (e) {
|
|
|
|
cb(e);
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
});
|
2017-01-30 15:44:47 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return hook;
|
|
|
|
};
|