import { Service } from '../../../../di/src/decorator/Service.ts' import {Collection} from '../../collection/Collection.ts' import Session from './Session.ts' import SessionManager, {InvalidSessionKeyError} from './SessionManager.ts' import Utility from '../../service/utility/Utility.ts' import SessionInterface from './SessionInterface.ts' /** * Type denoting a memory-stored session. */ export type SessionRegistrant = { key: string, session: SessionInterface } /** * Session manager object for memory-based sessions. * @extends SessionManager */ @Service() export default class MemorySessionManager extends SessionManager { /** * Collection of registered, in-memory sessions. * @type Collection */ private _sessions: Collection = new Collection() public async has_session(key: string): Promise { return !!this._sessions.firstWhere('key', '=', key) } public async get_session(key?: string): Promise { if ( !key ) { const utility: Utility = this.make(Utility) const session_key: string = key || utility.uuid() const session = this.make(Session) session.set_key(session_key) await session.persist() this._sessions.push({ key: session_key, session }) return session } const session = this._sessions.firstWhere('key', '=', key) if ( !session ) throw new InvalidSessionKeyError(key) return session.session } public async purge(key?: string) { if ( key ) { this._sessions = this._sessions.filter(session => session.key !== key) } else { this._sessions = new Collection() } } }