Add the Session handler, class, and middleware

This commit is contained in:
Dave Smith-Hayes 2024-03-18 22:59:49 -04:00
parent 9d2cb42e4b
commit 5162948e74

View File

@ -0,0 +1,45 @@
import { Context } from 'hono';
class Session {
private readonly id: string;
private data: Record<string, any>;
public constructor(id: string, data?: Record<string, any>) {
this.id = id;
this.data = data ?? {};
}
public getId(): string {
return this.id;
}
public getData(key: string): any {
return this.data[key];
}
public setData(key: string, data: any): void {
this.data[key] = data;
}
}
class SessionHandler {
private static instance: SessionHandler;
private constructor() { }
public static getInstance(): SessionHandler {
if (!SessionHandler.instance) {
SessionHandler.instance = new SessionHandler();
}
return SessionHandler.instance;
}
}
const sessionMiddleware = async (c: Context, next: CallableFunction) => {
c.set('session', SessionHandler.getInstance());
await next();
};
export { sessionMiddleware, SessionHandler, Session };