|
| 1 | +'use strict' |
| 2 | + |
| 3 | +/** |
| 4 | + * adonis-framework |
| 5 | + * |
| 6 | + * (c) Harminder Virk <virk@adonisjs.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | +*/ |
| 11 | + |
| 12 | +/** |
| 13 | + * Redis session driver to store sessions within |
| 14 | + * redis. |
| 15 | + * @class |
| 16 | + * @alias SessionRedisDriver |
| 17 | + */ |
| 18 | +class Redis { |
| 19 | + |
| 20 | + /** |
| 21 | + * Injects ['Adonis/Src/Helpers', 'Adonis/Src/Config'] |
| 22 | + */ |
| 23 | + static get inject () { |
| 24 | + return ['Adonis/Src/Helpers', 'Adonis/Src/Config', 'Adonis/Addons/RedisFactory'] |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * @constructor |
| 29 | + */ |
| 30 | + constructor (Helpers, Config, RedisFactory) { |
| 31 | + const redisConfig = Config.get('session.redis') |
| 32 | + this.ttl = Config.get('session.age') |
| 33 | + this.redis = new RedisFactory(redisConfig, Helpers, false) // do not use cluster for sessions |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Reads values for a session id from redis. |
| 38 | + * |
| 39 | + * @param {String} sessionId |
| 40 | + * |
| 41 | + * @return {Object} |
| 42 | + */ |
| 43 | + * read (sessionId) { |
| 44 | + try { |
| 45 | + const sessionValues = yield this.redis.get(sessionId) |
| 46 | + yield this.redis.expire(sessionId, this.ttl) // updating expiry after activity |
| 47 | + return JSON.parse(sessionValues) |
| 48 | + } catch (e) { |
| 49 | + return {} |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Writes values for a session id to redis. |
| 55 | + * |
| 56 | + * @param {String} sessionId |
| 57 | + * @param {Object} values |
| 58 | + * |
| 59 | + * @return {Boolean} |
| 60 | + */ |
| 61 | + * write (sessionId, values) { |
| 62 | + const response = yield this.redis.set(sessionId, JSON.stringify(values)) |
| 63 | + yield this.redis.expire(sessionId, this.ttl) |
| 64 | + return !!response |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Destorys the record of a given sessionId |
| 69 | + * |
| 70 | + * @param {String} sessionId |
| 71 | + * |
| 72 | + * @return {Boolean} [description] |
| 73 | + */ |
| 74 | + * destroy (sessionId) { |
| 75 | + const response = yield this.redis.del(sessionId) |
| 76 | + return !!response |
| 77 | + } |
| 78 | + |
| 79 | +} |
| 80 | + |
| 81 | +module.exports = Redis |
0 commit comments