redisStorage.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const Redis = require('ioredis');
  2. const redisConfig = require('../config/redisConfig');
  3. const { Store } = require('koa-session2');
  4. const cryptoUtil = require('../util/cryptoUtil');
  5. const log = require('../util/log');
  6. class RedisStore extends Store {
  7. constructor () {
  8. super();
  9. this.redis = new Redis(redisConfig);
  10. this.redis.on('connect', () => {
  11. log.debug(`connect redis success`);
  12. })
  13. }
  14. async get (sid, salt, ctx) {
  15. let data = await this.redis.get(`SESSION:${sid}`) || null;
  16. // log.debug(`[%s.get] get session success, sid: ${sid}`, this.constructor.name);
  17. return JSON.parse(data);
  18. }
  19. async set (session, { sid = cryptoUtil.encrypt(session), maxAge = 100000000 } = {}, ctx) {
  20. try {
  21. // Use redis set EX to automatically drop expired sessions
  22. await this.redis.set(`SESSION:${sid}`, JSON.stringify(session), 'EX', maxAge / 1000);
  23. log.debug(`[%s.set] set session success, sid: ${sid}`, this.constructor.name);
  24. } catch (e) {
  25. throw new Error(e);
  26. }
  27. return sid;
  28. }
  29. async destroy (sid, ctx) {
  30. log.debug(`destroy session ${sid}`);
  31. return await this.redis.del(`SESSION:${sid}`);
  32. }
  33. }
  34. module.exports = new RedisStore();