-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·83 lines (72 loc) · 1.88 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
/*!
* sessions-provider-redis
* Copyright(c) 2017 Fangdun Cai <cfddream@gmail.com> (https://fundon.me)
* MIT Licensed
*/
'use strict'
const redis = require('redis')
const parse = require('fast-json-parse')
const stringify = require('fast-safe-stringify')
const defaults = {
// Serializer
serializer: { parse, stringify },
// Redis client
client: undefined,
// Redis client options
clientOptions: undefined
}
module.exports = class RedisProvider {
constructor(options = {}) {
Object.keys(options).forEach(k => {
if (!(k in defaults)) delete options[k]
})
Object.assign(this, defaults, options)
if (!this.client) {
this.client = redis.createClient(this.clientOptions)
}
}
clear() {
return new Promise((resolve, reject) => {
this.client.flushdb(err => (err ? reject(err) : resolve()))
})
}
get(sid) {
return new Promise((resolve, reject) => {
this.client.get(sid, (error, data) => {
if (error) return reject(error)
if (!data) return resolve()
const { err, value } = this.serializer.parse(data)
if (err) return reject(err)
resolve(value)
})
})
}
has(sid) {
return new Promise((resolve, reject) => {
this.client.exists(
sid,
(err, data) => (err ? reject(err) : resolve(Boolean(data)))
)
})
}
set(sid, sess, expires) {
return new Promise((resolve, reject) => {
this.client.setex(
sid,
expires / 1000,
this.serializer.stringify(sess),
(err, data) => (err ? reject(err) : resolve(data))
)
})
}
delete(sid) {
return new Promise((resolve, reject) => {
this.client.del(sid, (err, data) => (err ? reject(err) : resolve(data)))
})
}
quit() {
return new Promise((resolve, reject) => {
this.client.quit((err, data) => (err ? reject(err) : resolve(data)))
})
}
}