session/lib/redis-store.js

73 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2020-09-18 18:25:56 +08:00
/**
* redis版会话管理
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 16:35:26
*/
2023-11-01 15:47:53 +08:00
import 'es.shim'
2020-09-24 19:56:01 +08:00
import Ioredis from 'ioredis'
2020-09-18 18:25:56 +08:00
export default class Session {
2023-10-27 19:18:04 +08:00
#store = null
#ttl = 60
2020-09-24 19:56:01 +08:00
constructor(opt) {
2023-10-27 19:18:04 +08:00
this.#store = new Ioredis({
2020-09-24 19:56:01 +08:00
host: opt.db.host || '127.0.0.1',
port: opt.db.port || 6379,
db: opt.db.db || 0
})
2023-10-27 19:18:04 +08:00
this.#ttl = opt.ttl
2020-09-18 18:25:56 +08:00
}
2023-10-27 19:18:04 +08:00
update(ssid) {
2020-09-18 18:25:56 +08:00
// 设置session有效期
2023-10-27 19:18:04 +08:00
this.#store.expire(ssid, this.#ttl)
2020-09-18 18:25:56 +08:00
}
// 获取session字段值, 需要await指令
2020-09-25 18:32:00 +08:00
get(ssid, key) {
2023-11-01 15:47:53 +08:00
let defer = Promise.defer()
2020-09-18 18:25:56 +08:00
2023-10-27 19:18:04 +08:00
this.#store.hgetall(ssid, (err, obj) => {
2020-09-18 18:25:56 +08:00
if (err) {
return defer.reject(err)
}
for (let i in obj) {
2020-09-24 19:56:01 +08:00
if (obj[i]) {
obj[i] = Number.parse(obj[i])
2020-09-18 18:25:56 +08:00
}
}
//不传key时,直接返回全部字段
2020-09-24 19:56:01 +08:00
if (key) {
2023-10-27 19:18:04 +08:00
defer.resolve(obj[key])
2020-09-24 19:56:01 +08:00
} else {
defer.resolve(obj)
2020-09-18 18:25:56 +08:00
}
})
return defer.promise
}
//设置session字段值
2020-09-25 18:32:00 +08:00
set(ssid, key, val) {
2020-09-18 18:25:56 +08:00
if (typeof key === 'object') {
for (let i in key) {
2023-10-27 19:18:04 +08:00
this.#store.hset(ssid, i, key[i])
2020-09-18 18:25:56 +08:00
}
} else {
2023-10-27 19:18:04 +08:00
this.#store.hset(ssid, key, val)
2020-09-18 18:25:56 +08:00
}
}
//删除单个字段
2020-09-25 18:32:00 +08:00
unset(ssid, key) {
2023-10-27 19:18:04 +08:00
this.#store.hdel(ssid, key)
2020-09-18 18:25:56 +08:00
}
//清除个人session
2020-09-25 18:32:00 +08:00
clear(ssid) {
2023-10-27 19:18:04 +08:00
this.#store.del(ssid)
2020-09-18 18:25:56 +08:00
}
}