▍ humdrum codex / soft
1.8 KB raw
 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
55
56
57
58
59
60
61
62
63
64
65
import type { SourceModule } from "../registry";
import {
  OnThisDayConfig,
  OnThisDayPayload,
  type OnThisDayConfig as Config,
  type OnThisDayPayload as Payload,
} from "@/lib/schemas/sources/onthisday";

interface WikiEntry {
  year?: number;
  text: string;
  pages?: Array<{ content_urls?: { desktop?: { page?: string } } }>;
}

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

function map(entries: WikiEntry[] = [], limit: number) {
  return entries.slice(0, limit).map((e) => ({
    year: e.year ?? null,
    text: e.text,
    link: e.pages?.[0]?.content_urls?.desktop?.page ?? null,
  }));
}

export const onThisDayModule: SourceModule<Config, Payload> = {
  kind: "onthisday",
  label: "On This Day",
  keyless: true,
  defaultRefreshSeconds: 86_400,
  configSchema: OnThisDayConfig,
  payloadSchema: OnThisDayPayload,

  async fetch({ config, signal }) {
    const now = new Date();
    const mm = String(now.getMonth() + 1).padStart(2, "0");
    const dd = String(now.getDate()).padStart(2, "0");

    const res = await fetch(
      `https://en.wikipedia.org/api/rest_v1/feed/onthisday/all/${mm}/${dd}`,
      {
        signal,
        headers: {
          "User-Agent": "PersonalDashboard/0.1 (local app)",
          Accept: "application/json",
        },
      },
    );
    if (!res.ok) throw new Error(`Wikipedia ${res.status}`);
    const j = (await res.json()) as {
      events?: WikiEntry[];
      births?: WikiEntry[];
      deaths?: WikiEntry[];
    };

    return {
      date: `${MONTHS[now.getMonth()]} ${now.getDate()}`,
      events: map(j.events, config.eventsLimit),
      births: map(j.births, config.birthsLimit),
      deaths: map(j.deaths, config.deathsLimit),
    };
  },
};