all files / modules/middleware/session/ CookieStore.js

100% Statements 17/17
80% Branches 8/10
100% Functions 3/3
100% Lines 17/17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                                                                 15×     15×          
const d = require("describe-property");
const Promise = require("../../utils/Promise");
 
/**
 * Client-side storage for sessions using HTTP cookies.
 *
 * Accepts the following options:
 *
 * - expireAfter      The number of seconds after which sessions expire.
 *                    Defaults to 0 (no expiration)
 *
 * Note: Cookies are only able to reliably store about 4k of data. Also, sending
 * and receiving large cookies can have a significant impact on overall server
 * response time (see http://yuiblog.com/blog/2007/03/01/performance-research-part-3/).
 * For these reasons, if you are planning on storing a lot of data in the session
 * you may want to use a server-side storage, such as mach.session.RedisStore.
 */
function CookieStore(options) {
    options = options || {};
 
    this.ttl = options.expireAfter
    ? 1000 * options.expireAfter // expireAfter is given in seconds
    : 0;
}
 
Object.defineProperties(CookieStore.prototype, {
 
    load: d(function (value) {
        let session;
        try {
            session = JSON.parse(value);
        } catch (error) {
      // Ignore invalid JSON data.
            return Promise.resolve({});
        }
 
    // Verify the session is not expired.
        if (session._expiry && session._expiry <= Date.now()) {
            return Promise.resolve({});
        }
 
        return Promise.resolve(session);
    }),
 
    save: d(function (session) {
        if (this.ttl) {
            session._expiry = Date.now() + this.ttl;
        }
 
        return Promise.resolve(JSON.stringify(session));
    })
 
});
 
module.exports = CookieStore;