2020-07-27 14:41:04 +00:00
|
|
|
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
|
|
|
|
|
2020-07-28 00:48:44 +00:00
|
|
|
const query = ModelClass.select(ModelClass.qualified_key_name())
|
2020-07-27 14:41:04 +00:00
|
|
|
.where(ModelClass.qualified_key_name(), '=', key)
|
2020-07-28 00:48:44 +00:00
|
|
|
|
|
|
|
return await query.exists()
|
2020-07-27 14:41:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|