import {SessionModel} from './SessionModel' import {Container} from '../../di' import {NoSessionKeyError, Session, SessionData, SessionNotLoadedError} from '../../http/session/Session' /** * An implementation of the Session driver whose records are stored in a database table. */ export class ORMSession extends Session { protected key?: string protected data?: SessionData protected session?: SessionModel public getKey(): string { if ( !this.key ) { throw new NoSessionKeyError() } return this.key } public setKey(key: string): void { this.key = key } public async load(): Promise { if ( !this.key ) { throw new NoSessionKeyError() } const session = await SessionModel.findByKey(this.key) if ( session ) { this.session = session this.data = this.session.json } else { this.session = Container.getContainer().make(SessionModel) this.session.uuid = this.key this.data = {} as SessionData } } public async persist(): Promise { if ( !this.key ) { throw new NoSessionKeyError() } if ( !this.data || !this.session ) { throw new SessionNotLoadedError() } this.session.uuid = this.key this.session.json = JSON.stringify(this.data) await this.session.save() } 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] } }