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.

62 lines
2.1 KiB

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'
/**
* Session manager that manages sessions using an ORM model.
* @extends SessionManager
*/
export default class ModelSessionManager extends SessionManager {
constructor(
/**
* The base model class to use for session lookups.
* @type StaticClass<SessionInterface, typeof Model>
*/
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()
}
}