daton/lib/src/http/session/ModelSessionManager.ts

54 lines
1.8 KiB
TypeScript
Raw Normal View History

import SessionManager, {InvalidSessionKeyError} from './SessionManager.ts'
import {Model} from '../../../../orm/src/model/Model.ts'
import SessionInterface, {isSessionInterface} from './SessionInterface.ts'
import {StaticClass} from '../../../../di/src/type/StaticClass.ts'
export default class ModelSessionManager extends SessionManager {
constructor(
protected readonly ModelClass: StaticClass<SessionInterface, typeof Model>,
) {
super()
}
public async get_session(key?: string): Promise<SessionInterface> {
const ModelClass: typeof Model = this.ModelClass as typeof Model
if ( !key ) {
const session = this.make(ModelClass)
await session.init_session()
if ( isSessionInterface(session) )
return session as SessionInterface
throw new TypeError(`Session model improperly implements the required SessionInterface.`)
}
const session = await ModelClass.find_by_key(key)
if ( !session ) throw new InvalidSessionKeyError(key)
if ( isSessionInterface(session) )
return session as SessionInterface
throw new TypeError(`Session model improperly implements the required SessionInterface.`)
}
public async has_session(key: string): Promise<boolean> {
const ModelClass: typeof Model = this.ModelClass as typeof Model
const query = ModelClass.select(ModelClass.qualified_key_name())
.where(ModelClass.qualified_key_name(), '=', key)
return await query.exists()
}
public async purge(key?: string): Promise<void> {
const ModelClass: typeof Model = this.ModelClass as typeof Model
const mutable = ModelClass.delete()
if ( key ) {
mutable.where(ModelClass.qualified_key_name(), '=', key)
}
await mutable.execute()
}
}