调整session的调用方式;增加index.d.ts

master
yutent 2025-01-03 15:34:42 +08:00
parent ebccbf270f
commit 4673b541a6
4 changed files with 106 additions and 65 deletions

38
index.d.ts vendored Normal file
View File

@ -0,0 +1,38 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2025/01/03 10:39:13
*/
declare interface RedisConfig {
host: string
port: number
db: number
}
declare interface SessionConfig {
ttl?: number
domain?: string
level?: 0 | 2 | 4 | 6
secret: string
db: RedisConfig
}
declare class Store {
update(ssid: string): void
get(ssid: string, key?: string): Promise<string | object>
set(ssid: string, key: string, val: string): void
unset(ssid: string, key: string): void
clear(ssid: string): void
}
declare interface Session {
name: 'session'
install(conf?: SessionConfig): Store
}
export function createSession(): Session

View File

@ -6,11 +6,11 @@
import { uuid, sha1 } from 'crypto.js'
import RedisStore from './lib/redis-store.js'
import Store from './lib/redis-store.js'
const DEFAULT_CONFIG = {
ttl: 3600 * 24 * 7,
domain: '', // NODESSID域, 默认等于domain
domain: '', // NODESSID域
level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip
secret: 'it_is_secret_key', // jwt密钥, 使用时请修改
db: {
@ -20,27 +20,7 @@ const DEFAULT_CONFIG = {
}
}
// 会话安装包
export const SessionModule = {
name: 'session',
install(conf = {}) {
if (!conf.secret) {
console.warn(
new Error(
'You must set a `secret` key for session, or it will use the default key.'
)
)
}
let session = Object.assign({}, DEFAULT_CONFIG, conf)
this.set({ session })
// 这里只创建session的存储器, 而初始化操作在中间件中进行
return new RedisStore(session)
}
}
// 会话中间件
export function createSession() {
return function (req, res, next) {
function sessionMiddleware(req, res, next) {
let opt = this.get('session')
let cache = req.cookie('NODESSID')
let deviceID = ''
@ -87,4 +67,27 @@ export function createSession() {
next()
}
// 会话中间件
export function createSession() {
return {
name: 'session',
install(conf = {}) {
if (!conf.secret) {
console.warn(
new Error(
'You must set a `secret` key for session, or it will use the default key.'
)
)
}
let session = Object.assign({}, DEFAULT_CONFIG, conf)
this.set({ session })
// 注册中间件
this.use(sessionMiddleware)
// 这里只创建session的存储器, 而初始化操作在中间件中进行
return new Store(session)
}
}
}

View File

@ -6,8 +6,7 @@
import 'es.shim'
import Ioredis from 'ioredis'
export default class Session {
export default class Store {
#store = null
#ttl = 60

View File

@ -1,10 +1,11 @@
{
"name": "@gm5/session",
"version": "2.0.0",
"version": "3.0.0",
"type": "module",
"description": "会话中间件。",
"main": "index.js",
"author": "yutent <yutent.io@gmail.com>",
"main": "index.js",
"types": "index.d.ts",
"keywords": [
"fivejs",
"gm5",