import {NoSessionKeyError, Session, SessionData, SessionNotLoadedError} from "./Session"; import {Injectable} from "@extollo/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) { 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 } }