-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkoa-session-mysql.js
executable file
·87 lines (70 loc) · 2.28 KB
/
koa-session-mysql.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const _db = require('mysql-magic');
const _genid = require('./lib/genid');
let _dbname = null;
let _table = null;
// delete expired session
function cleanupExpired(maxAge){
// retrieve connection scope
return _db.getConnection(_dbname, async function(db){
// run query - add maxAge in seconds
const [rows] = await db.query('DELETE FROM ?? WHERE `modified` > FROM_UNIXTIME(UNIX_TIMESTAMP() - ?);', [_table, maxAge/1000]);
// invalid ?
if (rows.length === 0){
return null;
}
// de-serialize
return JSON.parse(rows[0].payload);
});
}
// fetch
function retrieveSession(key, maxAge){
// retrieve connection scope
return _db.getConnection(_dbname, async function(db){
// run query - add maxAge in seconds
const [rows] = await db.query('SELECT `payload` FROM ?? WHERE `session_id` = ? AND `modified` > FROM_UNIXTIME(UNIX_TIMESTAMP() - ?) LIMIT 1;', [_table, key, maxAge/1000]);
// invalid ?
if (rows.length === 0){
return null;
}
// de-serialize
return JSON.parse(rows[0].payload);
});
}
// store
function storeSession(key, sess){
// retrieve connection scope
return _db.getConnection(_dbname, function(db){
// serialize
const payload = JSON.stringify(sess);
// upsert
const query = 'INSERT INTO ?? (session_id, modified, payload) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE session_id=?, modified=?, payload=?';
// modified
const now = new Date();
// run query
return db.query(query, [_table, key, now, payload, key, now, payload]);
});
}
// drop session
function destroySession(key){
// retrieve connection scope
return _db.getConnection(_dbname, async function(db){
// try to destroy session
const [result] = await db.query('DELETE FROM ?? WHERE `session_id` = ? LIMIT 1;', [_table, key]);
// session deleted ?
return result.affectedRows > 0;
});
}
function init(dbpool, table){
// get db pool by name
_dbname = dbpool;
// store table name
_table = table;
}
module.exports = {
init: init,
get: retrieveSession,
set: storeSession,
destroy: destroySession,
cleanup: cleanupExpired,
genid: _genid
}