Files
lib/src/http/session/Session.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-03-07 13:26:14 -06:00
import {Injectable, Inject} from "@extollo/di"
import {ErrorWithContext} from "@extollo/util"
import {Request} from "../lifecycle/Request"
2021-03-25 08:50:13 -05:00
/**
* Type alias describing some inflated session data.
*/
2021-03-07 13:26:14 -06:00
export type SessionData = {[key: string]: any}
2021-03-25 08:50:13 -05:00
/**
* Error thrown when a session is requested for a key that does not exist.
*/
2021-03-07 13:26:14 -06:00
export class NoSessionKeyError extends ErrorWithContext {
constructor() {
super('No session ID has been set.')
}
}
2021-03-25 08:50:13 -05:00
/**
* Error thrown when a session operation is performed before the session has been loaded.
*/
2021-03-07 13:26:14 -06:00
export class SessionNotLoadedError extends ErrorWithContext {
constructor() {
super('Cannot access session data; data is not loaded.')
}
}
2021-03-25 08:50:13 -05:00
/**
* An abstract class representing a session driver.
* Some implementation of this is injected into the request.
*/
2021-03-07 13:26:14 -06:00
@Injectable()
export abstract class Session {
@Inject()
protected readonly request!: Request
2021-03-25 08:50:13 -05:00
/** Get the unique key of this session. */
2021-03-07 13:26:14 -06:00
public abstract getKey(): string
2021-03-25 08:50:13 -05:00
/** Set a unique key of this session. */
2021-03-07 13:26:14 -06:00
public abstract setKey(key: string): void
2021-03-25 08:50:13 -05:00
/** Load the session data from the respective backend. */
2021-03-07 13:26:14 -06:00
public abstract load(): void | Promise<void>
2021-03-25 08:50:13 -05:00
/** Save the session data into the respective backend. */
2021-03-07 13:26:14 -06:00
public abstract persist(): void | Promise<void>
2021-03-25 08:50:13 -05:00
/** Get the loaded session data as an object. */
2021-03-07 13:26:14 -06:00
public abstract getData(): SessionData
2021-03-25 08:50:13 -05:00
/** Bulk set an object as the session data. */
2021-03-07 13:26:14 -06:00
public abstract setData(data: SessionData): void
2021-03-25 08:50:13 -05:00
/** Get a value from the session by key. */
2021-03-07 13:26:14 -06:00
public abstract get(key: string, fallback?: any): any
2021-03-25 08:50:13 -05:00
/** Set a value in the session by key. */
2021-03-07 13:26:14 -06:00
public abstract set(key: string, value: any): void
}