session/lib/mem-store.js

65 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-09-18 18:25:56 +08:00
/**
* 内存版会话管理(仅用于测试,数据)
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 16:35:26
*/
function hideProperty(host, name, value) {
Object.defineProperty(host, name, {
value: value,
writable: true,
enumerable: false,
configurable: true
})
}
export default class Session {
2020-09-24 19:56:01 +08:00
constructor(opt) {
this.store = Object.create(null)
this.ttl = opt.ttl
2020-09-18 18:25:56 +08:00
}
2020-09-25 18:32:00 +08:00
start(ssid) {
2020-09-24 19:56:01 +08:00
var session = this.store[ssid]
// 内存版会话管理, 没有设计计划任务来清理过期数据
// 需要在初始化时先判断, 过期的自动清除, 没过期的, 直接重新续期
if (session) {
if (Date.now() > session.__expires__) {
2020-09-25 18:32:00 +08:00
this.clear(ssid)
2020-09-24 19:56:01 +08:00
}
} else {
session = this.store[ssid] = {}
2020-09-18 18:25:56 +08:00
}
2020-09-24 19:56:01 +08:00
// 设置session有效期
hideProperty(session, '__expires__', Date.now() + this.ttl * 1000)
2020-09-18 18:25:56 +08:00
}
// 获取session字段值
2020-09-25 18:32:00 +08:00
get(ssid, key) {
return key ? this.store[ssid][key] || null : this.store[ssid]
2020-09-18 18:25:56 +08:00
}
// 设置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) {
2020-09-25 18:32:00 +08:00
this.store[ssid][i] = key[i]
2020-09-18 18:25:56 +08:00
}
} else {
2020-09-25 18:32:00 +08:00
this.store[ssid][key] = val
2020-09-18 18:25:56 +08:00
}
}
// 删除单个字段
2020-09-25 18:32:00 +08:00
unset(ssid, key) {
delete this.store[ssid][key]
2020-09-18 18:25:56 +08:00
}
// 清除个人session
2020-09-25 18:32:00 +08:00
clear(ssid) {
this.store[ssid] = {}
2020-09-18 18:25:56 +08:00
}
}