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.

55 lines
1.8 KiB

import { Service } from '../../../../di/src/decorator/Service.ts'
import {Collection} from '../../collection/Collection.ts'
import Session from './Session.ts'
import SessionManager, {InvalidSessionKeyError} from './SessionManager.ts'
import Utility from '../../service/utility/Utility.ts'
import SessionInterface from './SessionInterface.ts'
/**
* Type denoting a memory-stored session.
*/
export type SessionRegistrant = { key: string, session: SessionInterface }
/**
* Session manager object for memory-based sessions.
* @extends SessionManager
*/
@Service()
export default class MemorySessionManager extends SessionManager {
/**
* Collection of registered, in-memory sessions.
* @type Collection<SessionRegistrant>
*/
private _sessions: Collection<SessionRegistrant> = new Collection<SessionRegistrant>()
public async has_session(key: string): Promise<boolean> {
return !!this._sessions.firstWhere('key', '=', key)
}
public async get_session(key?: string): Promise<SessionInterface> {
if ( !key ) {
const utility: Utility = this.make(Utility)
const session_key: string = key || utility.uuid()
const session = this.make(Session)
session.set_key(session_key)
await session.persist()
this._sessions.push({ key: session_key, session })
return session
}
const session = this._sessions.firstWhere('key', '=', key)
if ( !session ) throw new InvalidSessionKeyError(key)
return session.session
}
public async purge(key?: string) {
if ( key ) {
this._sessions = this._sessions.filter(session => session.key !== key)
} else {
this._sessions = new Collection<SessionRegistrant>()
}
}
}