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/orm/support/ORMSession.ts

91 lines
2.2 KiB

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<void> {
if ( !this.key ) {
throw new NoSessionKeyError()
}
const session = <SessionModel> await SessionModel.findByKey(this.key)
if ( session ) {
this.session = session
this.data = this.session.json
} else {
this.session = <SessionModel> Container.getContainer().make(SessionModel)
this.session.sessionUuid = this.key
this.data = {} as SessionData
}
}
public async persist(): Promise<void> {
if ( !this.key ) {
throw new NoSessionKeyError()
}
if ( !this.data || !this.session ) {
throw new SessionNotLoadedError()
}
this.session.sessionUuid = 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]
}
}