From 5162948e7470ba0003c0c5682b755376b27d62bf Mon Sep 17 00:00:00 2001 From: Dave Smith-Hayes Date: Mon, 18 Mar 2024 22:59:49 -0400 Subject: [PATCH] Add the Session handler, class, and middleware --- app/src/middleware/session.ts | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 app/src/middleware/session.ts diff --git a/app/src/middleware/session.ts b/app/src/middleware/session.ts new file mode 100644 index 0000000..20cbe42 --- /dev/null +++ b/app/src/middleware/session.ts @@ -0,0 +1,45 @@ +import { Context } from 'hono'; + +class Session { + private readonly id: string; + private data: Record; + + public constructor(id: string, data?: Record) { + 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 }; +