|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } |
| 4 | + |
| 5 | +var Redis = _interopDefault(require('redis')); |
| 6 | + |
| 7 | +const redisStore = (...args) => { |
| 8 | + const redisCache = Redis.createClient(...args); |
| 9 | + const storeArgs = redisCache.options; |
| 10 | + |
| 11 | + return { |
| 12 | + name: 'redis', |
| 13 | + getClient: () => redisCache, |
| 14 | + set: (key, value, options, cb) => ( |
| 15 | + new Promise((resolve, reject) => { |
| 16 | + if (typeof options === 'function') { |
| 17 | + cb = options; |
| 18 | + options = {}; |
| 19 | + } |
| 20 | + options = options || {}; |
| 21 | + |
| 22 | + if (!cb) { |
| 23 | + cb = (err, result) => (err ? reject(err) : resolve(result)); |
| 24 | + } |
| 25 | + |
| 26 | + const ttl = (options.ttl || options.ttl === 0) ? options.ttl : storeArgs.ttl; |
| 27 | + const val = JSON.stringify(value) || '"undefined"'; |
| 28 | + |
| 29 | + if (ttl) { |
| 30 | + redisCache.setex(key, ttl, val, handleResponse(cb)); |
| 31 | + } else { |
| 32 | + redisCache.set(key, val, handleResponse(cb)); |
| 33 | + } |
| 34 | + }) |
| 35 | + ), |
| 36 | + get: (key, options, cb) => ( |
| 37 | + new Promise((resolve, reject) => { |
| 38 | + if (typeof options === 'function') { |
| 39 | + cb = options; |
| 40 | + } |
| 41 | + |
| 42 | + if (!cb) { |
| 43 | + cb = (err, result) => (err ? reject(err) : resolve(result)); |
| 44 | + } |
| 45 | + |
| 46 | + redisCache.get(key, handleResponse(cb, { parse: true })); |
| 47 | + }) |
| 48 | + ), |
| 49 | + del: (key, options, cb) => { |
| 50 | + if (typeof options === 'function') { |
| 51 | + cb = options; |
| 52 | + } |
| 53 | + |
| 54 | + redisCache.del(key, handleResponse(cb)); |
| 55 | + }, |
| 56 | + reset: cb => redisCache.flushdb(handleResponse(cb)), |
| 57 | + keys: cb => redisCache.keys(handleResponse(cb)), |
| 58 | + ttl: (key, cb) => redisCache.ttl(key, handleResponse(cb)), |
| 59 | + isCacheableValue: args.isCacheableValue || (value => value !== undefined && value !== null), |
| 60 | + }; |
| 61 | +}; |
| 62 | + |
| 63 | +function handleResponse(cb, opts = {}) { |
| 64 | + return (err, result) => { |
| 65 | + if (err) { |
| 66 | + return cb && cb(err); |
| 67 | + } |
| 68 | + |
| 69 | + if (opts.parse) { |
| 70 | + try { |
| 71 | + result = JSON.parse(result); |
| 72 | + } catch (e) { |
| 73 | + return cb && cb(e); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return cb && cb(null, result); |
| 78 | + }; |
| 79 | +} |
| 80 | + |
| 81 | +const methods = { |
| 82 | + create: (...args) => redisStore(...args), |
| 83 | +}; |
| 84 | + |
| 85 | +module.exports = methods; |
0 commit comments