Import other modules into monorepo
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
68
src/orm/support/ORMSession.ts
Normal file
68
src/orm/support/ORMSession.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user