You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.7 KiB
64 lines
1.7 KiB
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
|
|
|
|
constructor() { super() }
|
|
|
|
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
|
|
}
|
|
}
|