-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (84 loc) · 2.86 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
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
88
const debug = require('debug');
const log = debug('file-mysql-session:log');
log.error = debug('file-mysql-session:error');
log.debug = debug('file-mysql-session:debug');
module.exports = function (session) {
const FileBackedUpSession = require('file-backedup-session')(session);
function fileMySQLSession(options) {
options = {
dir: 'sessions',
createTable: true,
table: 'sessions',
backupInterval: 60000,
retryLimit: 100,
retryWait: 100,
log,
...options,
}
options.getSessions = () => new Promise((resolve, reject) => {
options.connection.query(
`SELECT session_id, data FROM ${options.table};`,
(err, results) => {
if (err) {
reject(err);
} else {
resolve(results);
}
}
)
});
options.deleteSessions = ids => new Promise((resolve, reject) => {
options.connection.query(
`DELETE FROM ${options.table} WHERE session_id IN (?);`,
ids,
err => {
if (err) {
reject(err);
} else {
resolve();
}
}
);
});
options.insertOrUpdateSessions = sessions => new Promise((resolve, reject) => {
options.connection.query(
Array(sessions).fill(
`INSERT INTO ${options.table} (session_id, expires, data) VALUES (?,?,?)
ON DUPLICATE KEY UPDATE expires=?, data=?`
).join(';'),
sessions.map(({id, expires, data}) => [
id,
expires,
data,
expires,
data,
]).reduce((a, b) => a.concat(b)),
err => {
if (err) {
reject(err);
} else {
resolve();
}
}
);
});
options.setupBackup = options.createTable && (() => new Promise((resolve, reject) => {
options.connection.query(
`CREATE TABLE IF NOT EXISTS ${options.table} (
session_id VARCHAR(128) PRIMARY KEY NOT NULL,
expires INT(11) UNSIGNED NOT NULL,
data TEXT
);`,
err => {
if (err) {
reject(err);
} else {
resolve();
}
}
);
}));
return new FileBackedUpSession(options);
}
return fileMySQLSession;
};