session/lib/redis-store.js

70 lines
1.3 KiB
JavaScript
Raw 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
*/
2020-09-24 19:56:01 +08:00
import Ioredis from 'ioredis'
2020-09-18 18:25:56 +08:00
export default class Session {
2020-09-24 19:56:01 +08:00
constructor(opt) {
this.store = new RedisStore({
host: opt.db.host || '127.0.0.1',
port: opt.db.port || 6379,
db: opt.db.db || 0
})
this.ttl = opt.ttl
2020-09-18 18:25:56 +08:00
}
2020-09-24 19:56:01 +08:00
start(ssid) {
2020-09-18 18:25:56 +08:00
this.ssid = ssid
// 设置session有效期
2020-09-24 19:56:01 +08:00
this.store.expire(ssid, this.ttl)
2020-09-18 18:25:56 +08:00
}
// 获取session字段值, 需要await指令
get(key) {
var defer = Promise.defer()
this.store.hgetall(this.ssid, (err, obj) => {
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) {
2020-09-18 18:25:56 +08:00
defer.resolve(obj.hasOwnProperty(key) ? obj[key] : null)
2020-09-24 19:56:01 +08:00
} else {
defer.resolve(obj)
2020-09-18 18:25:56 +08:00
}
})
return defer.promise
}
//设置session字段值
set(key, val) {
if (typeof key === 'object') {
for (let i in key) {
this.store.hset(this.ssid, i, key[i])
}
} else {
this.store.hset(this.ssid, key, val)
}
}
//删除单个字段
unset(key) {
this.store.hdel(this.ssid, key)
}
//清除个人session
clear() {
this.store.del(this.ssid)
}
}