💾 Archived View for iich.space › src › middleware › createSessionHandler.ts captured on 2022-03-01 at 15:59:59.

View Raw

More Information

⬅️ Previous capture (2021-12-03)

-=-=-=-=-=-=-

import { Request, Response } from '@/gemini';
import { Handler } from '@/mission-control';

export type SessionHandler<T> = (
  request: Request,
  response: Response,
  session: T,
) => void | Promise<void>;

const withSession = <T>(
  sessions: Map<string, T>,
  empty: T,
  request: Request,
) => {
  if (request.fingerprint === null) {
    throw new Error('Missing Certificate');
  }

  const key = request.fingerprint;

  let session = sessions.get(key);

  if (session === undefined) {
    session = { ...empty };
    sessions.set(key, session);
  }

  return session;
};

type WrappedHandler<T> = (handler: SessionHandler<T>) => Handler;

const createSessionHandler = <T>(empty: T): WrappedHandler<T> => {
  const sessions = new Map<string, T>();

  return (handler: SessionHandler<T>) =>
    (request: Request, response: Response) =>
      handler(request, response, withSession(sessions, empty, request));
};

export default createSessionHandler;