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

95.23% Statements 20/21
66.66% Branches 8/12
100% Functions 4/4
100% Lines 17/17

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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54              11x       2x 2x 2x 217122x   2x         4x 2x 2x 2x             2x         2x       2x 2x         3x       3x 2x    
import { eq } from 'drizzle-orm';
import { openDatabase } from '../db/client.ts';
import { courseScore, score } from '../db/schema.ts';
import { ICONS } from './icons.generated.ts';
import type { PageContext } from './page.ts';
 
/** Card URLs carry a version, so caches keep them; a play without its own card falls back to the default one. */
const CARD_CACHE = 'public, max-age=86400';
 
let defaultCard: Uint8Array<ArrayBuffer> | undefined;
function defaultCardBytes(): Uint8Array<ArrayBuffer> {
  Eif (defaultCard === undefined) {
    const text = atob(ICONS.ogDefault.base64);
    defaultCard = new Uint8Array(text.length);
    for (let i = 0; i < text.length; i++) defaultCard[i] = text.charCodeAt(i);
  }
  return defaultCard;
}
 
/** A stored card, or the site's default card when there is none (or its object is gone). */
async function cardResponse(c: PageContext, cardKey: string | null) {
  if (cardKey !== null) {
    const object = await c.env.BLOBS.get(cardKey);
    Eif (object !== null) {
      return c.body(object.body, 200, {
        'content-type': object.httpMetadata?.contentType ?? 'application/octet-stream',
        'cache-control': CARD_CACHE,
        'x-content-type-options': 'nosniff',
      });
    }
  }
  return c.body(defaultCardBytes(), 200, { 'content-type': 'image/png', 'cache-control': CARD_CACHE });
}
 
/** A play's share card (og:image): the one its player's browser drew, or the site's default card. */
export async function scoreCardImage(c: PageContext<'/scores/:id/card'>) {
  const found = await openDatabase(c.env.DB).query.score.findFirst({
    where: eq(score.id, c.req.param('id')),
    columns: { cardKey: true },
  });
  Iif (found === undefined) return c.body('Not Found', 404);
  return cardResponse(c, found.cardKey);
}
 
/** A course run's share card (og:image), as `scoreCardImage`. */
export async function courseScoreCardImage(c: PageContext<'/course-scores/:id/card'>) {
  const found = await openDatabase(c.env.DB).query.courseScore.findFirst({
    where: eq(courseScore.id, c.req.param('id')),
    columns: { cardKey: true },
  });
  if (found === undefined) return c.body('Not Found', 404);
  return cardResponse(c, found.cardKey);
}