UNPKG

1.8 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * Session model.
5 */
6
7class Session {
8 /**
9 * Session constructor
10 * @param {Context} ctx
11 * @param {Object} obj
12 * @api private
13 */
14
15 constructor(ctx, obj) {
16 this._ctx = ctx;
17 if (!obj) {
18 this.isNew = true;
19 } else {
20 for (const k in obj) {
21 // restore maxAge from store
22 if (k === '_maxAge') this._ctx.sessionOptions.maxAge = obj._maxAge;
23 else this[k] = obj[k];
24 }
25 }
26 }
27
28 /**
29 * JSON representation of the session.
30 *
31 * @return {Object}
32 * @api public
33 */
34
35 toJSON() {
36 const obj = {};
37
38 Object.keys(this).forEach(key => {
39 if (key === 'isNew') return;
40 if (key[0] === '_') return;
41 obj[key] = this[key];
42 });
43
44 return obj;
45 }
46
47 /**
48 *
49 * alias to `toJSON`
50 * @api public
51 */
52
53 inspect() {
54 return this.toJSON();
55 }
56
57 /**
58 * Return how many values there are in the session object.
59 * Used to see if it's "populated".
60 *
61 * @return {Number}
62 * @api public
63 */
64
65 get length() {
66 return Object.keys(this.toJSON()).length;
67 }
68
69 /**
70 * populated flag, which is just a boolean alias of .length.
71 *
72 * @return {Boolean}
73 * @api public
74 */
75
76 get populated() {
77 return !!this.length;
78 }
79
80 /**
81 * get session maxAge
82 *
83 * @return {Number}
84 * @api public
85 */
86
87 get maxAge() {
88 return this._ctx.sessionOptions.maxAge;
89 }
90
91 /**
92 * set session maxAge
93 *
94 * @param {Number}
95 * @api public
96 */
97
98 set maxAge(val) {
99 this._ctx.sessionOptions.maxAge = val;
100 // maxAge changed, must save to cookie and store
101 this._requireSave = true;
102 }
103
104 /**
105 * save this session no matter whether it is populated
106 *
107 * @api public
108 */
109
110 save() {
111 this._requireSave = true;
112 }
113}
114
115module.exports = Session;