|
| 1 | +'use strict' |
| 2 | + |
| 3 | +// Note: redis-server must be available in PATH |
| 4 | +const tmpRedis = require('haredis-tmp') |
| 5 | + |
| 6 | +module.exports = function inject (ioredis) { |
| 7 | + return function (location, options, callback) { |
| 8 | + let redis |
| 9 | + let shutdown |
| 10 | + |
| 11 | + // Expire keys (which is cheap) to avoid blowing up memory |
| 12 | + const ttlSeconds = options.ttl || 10 |
| 13 | + const port = options.port || 6389 |
| 14 | + |
| 15 | + // "For better performance. Recommended to be enabled when handling large |
| 16 | + // array response and you don't need the buffer support." |
| 17 | + const dropBufferSupport = !!options.dropBufferSupport |
| 18 | + |
| 19 | + const wrapper = { |
| 20 | + status: 'new', |
| 21 | + |
| 22 | + open: function (options, callback) { |
| 23 | + wrapper.status = 'opening' |
| 24 | + |
| 25 | + tmpRedis([port], { verbose: true }, function (err, path, shutdown_) { |
| 26 | + if (err) return callback(err) |
| 27 | + |
| 28 | + shutdown = shutdown_ |
| 29 | + redis = new ioredis({ |
| 30 | + port, |
| 31 | + retryStrategy: () => false, |
| 32 | + maxRetriesPerRequest: 0, |
| 33 | + autoResubscribe: false, |
| 34 | + autoResendUnfulfilledCommands: false, |
| 35 | + enableOfflineQueue: false, |
| 36 | + dropBufferSupport |
| 37 | + }) |
| 38 | + |
| 39 | + redis.once('ready', function () { |
| 40 | + wrapper.status = 'open' |
| 41 | + callback(null, wrapper) |
| 42 | + }) |
| 43 | + |
| 44 | + // ioredis swallows errors if there's no listener |
| 45 | + redis.on('error', function (err) { |
| 46 | + throw err |
| 47 | + }) |
| 48 | + }) |
| 49 | + }, |
| 50 | + |
| 51 | + put: function (key, value/*, options */, callback) { |
| 52 | + redis.set(key, value, 'EX', ttlSeconds, callback) |
| 53 | + }, |
| 54 | + |
| 55 | + close: function (callback) { |
| 56 | + redis.disconnect() |
| 57 | + shutdown(callback) |
| 58 | + }, |
| 59 | + |
| 60 | + // Trick reachdown |
| 61 | + _iterator: function () {} |
| 62 | + } |
| 63 | + |
| 64 | + return wrapper |
| 65 | + } |
| 66 | +} |
0 commit comments