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

69 lines
1.9 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() {
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.uuid = this.key
this.data = {} as SessionData
}
}
public async persist() {
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() {
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
}
}