store.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**!
  2. * koa-generic-session - lib/store.js
  3. * Copyright(c) 2014
  4. * MIT Licensed
  5. *
  6. * Authors:
  7. * dead_horse <dead_horse@qq.com> (http://deadhorse.me)
  8. */
  9. 'use strict';
  10. /**
  11. * Module dependencies.
  12. */
  13. var util = require('util');
  14. var EventEmitter = require('events').EventEmitter;
  15. var debug = require('debug')('koa-generic-session:store');
  16. var copy = require('copy-to');
  17. var defaultOptions = {
  18. prefix: 'koa:sess:'
  19. };
  20. function Store(client, options) {
  21. this.client = client;
  22. this.options = {};
  23. copy(options).and(defaultOptions).to(this.options);
  24. EventEmitter.call(this);
  25. // delegate client connect / disconnect event
  26. if (typeof client.on === 'function') {
  27. client.on('disconnect', this.emit.bind(this, 'disconnect'));
  28. client.on('connect', this.emit.bind(this, 'connect'));
  29. }
  30. }
  31. util.inherits(Store, EventEmitter);
  32. Store.prototype.get = function *(sid) {
  33. var data;
  34. sid = this.options.prefix + sid;
  35. debug('GET %s', sid);
  36. data = yield this.client.get(sid);
  37. if (!data) {
  38. debug('GET empty');
  39. return null;
  40. }
  41. if (data && data.cookie && typeof data.cookie.expires === 'string') {
  42. // make sure data.cookie.expires is a Date
  43. data.cookie.expires = new Date(data.cookie.expires);
  44. }
  45. debug('GOT %j', data);
  46. return data;
  47. };
  48. Store.prototype.set = function *(sid, sess) {
  49. var ttl = this.options.ttl;
  50. if (!ttl) {
  51. var maxage = sess.cookie && sess.cookie.maxage;
  52. if (typeof maxage === 'number') {
  53. ttl = maxage;
  54. }
  55. // if has cookie.expires, ignore cookie.maxage
  56. if (sess.cookie && sess.cookie.expires) {
  57. ttl = Math.ceil(sess.cookie.expires.getTime() - Date.now());
  58. }
  59. }
  60. sid = this.options.prefix + sid;
  61. debug('SET key: %s, value: %s, ttl: %d', sid, sess, ttl);
  62. yield this.client.set(sid, sess, ttl);
  63. debug('SET complete');
  64. };
  65. Store.prototype.destroy = function *(sid) {
  66. sid = this.options.prefix + sid;
  67. debug('DEL %s', sid);
  68. yield this.client.destroy(sid);
  69. debug('DEL %s complete', sid);
  70. };
  71. module.exports = Store;