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.
lib/src/http/session/MemorySession.ts

105 lines
2.5 KiB

import {NoSessionKeyError, Session, SessionData, SessionNotLoadedError} from './Session'
import {Injectable} from '../../di'
/**
* Implementation of the session driver that stores session data in memory.
* This is the default, for compatibility, but it is recommended that you replace
* this driver with one with a persistent backend.
*/
@Injectable()
export class MemorySession extends Session {
/** Mapping of session key to session data object. */
private static sessionsByID: {[key: string]: SessionData} = {}
/** Get a particular session by ID. */
private static getSession(id: string) {
if ( !this.sessionsByID[id] ) {
this.sessionsByID[id] = {} as SessionData
}
return this.sessionsByID[id]
}
/** Store the given session data by its ID. */
private static setSession(id: string, data: SessionData) {
this.sessionsByID[id] = data
}
/** The ID of this session. */
protected sessionID?: string
/** The associated data for this session. */
protected data?: SessionData
constructor() {
super()
}
public getKey(): string {
if ( !this.sessionID ) {
throw new NoSessionKeyError()
}
return this.sessionID
}
public setKey(key: string): void {
this.sessionID = key
}
public load(): void {
if ( !this.sessionID ) {
throw new NoSessionKeyError()
}
this.data = MemorySession.getSession(this.sessionID)
}
public persist(): void {
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): void {
this.data = data
}
public get(key: string, fallback?: unknown): any {
if ( !this.data ) {
throw new SessionNotLoadedError()
}
return this.data?.[key] ?? fallback
}
public set(key: string, value: unknown): void {
if ( !this.data ) {
throw new SessionNotLoadedError()
}
this.data[key] = value
}
public forget(key: string): void {
if ( !this.data ) {
throw new SessionNotLoadedError()
}
delete this.data[key]
}
}