forked from Secbone/koa-session2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (34 loc) · 1.2 KB
/
index.js
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
const Store = require('./libs/store.js');
module.exports = (opts = {}) => {
const { key = "koa:sess", store = new Store(), onlyJSON = true } = opts;
return async (ctx, next) => {
let id = ctx.cookies.get(key, opts);
if(!id) {
ctx.session = {};
} else {
ctx.session = await store.get(id);
// check session must be a no-null object
if(typeof ctx.session !== "object" || ctx.session == null) {
ctx.session = {};
}
}
const old = JSON.stringify(ctx.session);
await next();
// if not changed
if(old == JSON.stringify(ctx.session)) return;
// if is an empty object
if(ctx.session instanceof Object && !Object.keys(ctx.session).length) {
ctx.session = null;
}
// need clear old session
if(id && !ctx.session) {
await store.destroy(id);
return;
}
// set/update session
const sid = await store.set(ctx.session, Object.assign({}, opts, {sid: id}));
ctx.cookies.set(key, sid, opts);
}
}
// Reeexport Store to not use reference to internal files
module.exports.Store = Store;