Add basic memory-based session driver

This commit is contained in:
2021-03-07 13:26:14 -06:00
parent fdcd80a43e
commit 338b9be506
7 changed files with 202 additions and 1 deletions

View File

@@ -0,0 +1,61 @@
import {NoSessionKeyError, Session, SessionData, SessionNotLoadedError} from "./Session";
import {Injectable} from "@extollo/di";
@Injectable()
export class MemorySession extends Session {
private static sessionsByID: {[key: string]: SessionData} = {}
private static getSession(id: string) {
if ( !this.sessionsByID[id] ) {
this.sessionsByID[id] = {} as SessionData
}
return this.sessionsByID[id]
}
private static setSession(id: string, data: SessionData) {
this.sessionsByID[id] = data
}
protected sessionID?: string
protected data?: SessionData
public getKey(): string {
if ( !this.sessionID ) throw new NoSessionKeyError()
return this.sessionID
}
public setKey(key: string) {
this.sessionID = key
}
public load() {
if ( !this.sessionID ) throw new NoSessionKeyError()
this.data = MemorySession.getSession(this.sessionID)
}
public persist() {
if ( !this.sessionID ) throw new NoSessionKeyError()
if ( !this.data ) throw new SessionNotLoadedError()
MemorySession.setSession(this.sessionID, this.data)
}
public getData(): SessionData {
if ( !this.data ) throw new SessionNotLoadedError()
return this.data
}
public setData(data: SessionData) {
this.data = data
}
public get(key: string, fallback?: any): any {
if ( !this.data ) throw new SessionNotLoadedError()
return this.data?.[key] ?? fallback
}
public set(key: string, value: any) {
if ( !this.data ) throw new SessionNotLoadedError()
this.data[key] = value
}
}