All files / app-leaderboard/src/pages viewer.ts

100% Statements 12/12
90% Branches 9/10
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                      144x                       11x 144x 144x 144x 131x 131x 131x 30x 30x     144x 144x    
import type { MiddlewareHandler } from 'hono';
import { loadAccount, type AccountSummary } from '../accounts.ts';
import type { AppEnv } from '../app.ts';
import { loadSession, passOnSetCookies } from '../auth.ts';
import { openDatabase } from '../db/client.ts';
 
/** Who is looking at a page: their account (and its id, to show them what only they may see), or null when signed out. */
export type Viewer = AccountSummary & { userId: string };
 
/** Paths that never show the viewer (assets, icons, the manifest): no session lookup for them. */
function needsViewer(path: string): boolean {
  return (
    !path.startsWith('/assets/') &&
    !path.endsWith('/avatar') &&
    !path.endsWith('/card') &&
    !path.endsWith('.webmanifest')
  );
}
 
/**
 * Reads the session cookie for the pages, so the header can show the signed-in player. The cookie is the one the
 * player and the API share (same origin); pages are private and revalidated, so showing it is safe.
 */
export const loadViewer: MiddlewareHandler<AppEnv> = async (c, next) => {
  c.set('viewer', null);
  let setCookies: string[] = [];
  if (needsViewer(c.req.path)) {
    const loaded = await loadSession(c.env, c.req.raw);
    setCookies = loaded.setCookies;
    if (loaded.session !== null) {
      const account = await loadAccount(openDatabase(c.env.DB), loaded.session.user.id);
      c.set('viewer', account === undefined ? null : { ...account, userId: loaded.session.user.id });
    }
  }
  await next();
  passOnSetCookies(c.res, setCookies);
};