web/src/utils/fetch-lastmod.ts
58 lines · 1983 bytes
4 symbols in this file
1import { fetchChangelog } from './fetch-changelog';
2import { slugify } from './fetch-data';
3import type { ChangelogEntry } from './fetch-changelog';
4
5type Crumbs = Array<string | undefined>;
6
7/**
8 * Really over-complicated way to get the last modified date from changelog
9 * for any given page, for the sitemap to be accurate and correct
10 * (even tho no one uses the lastmod field)
11 */
12const listChanged = ({
13 services,
14 sections,
15 categories,
16}: ChangelogEntry['changes']): Crumbs[] => [
17 ...[
18 ...(services?.added || []),
19 ...(services?.removed || []),
20 ...(services?.modified || []),
21 ].map((s) => [s.category, s.section, s.name]),
22 ...[...(services?.moved || []), ...(services?.renamed || [])].flatMap((s) => [
23 [s.from.category, s.from.section, s.name],
24 [s.to.category, s.to.section, s.name],
25 ]),
26 ...[...(sections?.added || []), ...(sections?.removed || [])].map((s) => [
27 s.category,
28 s.name,
29 ]),
30 ...(sections?.moved || []).flatMap((s) => [
31 [s.from.category, s.from.section],
32 [s.to.category, s.to.section],
33 ]),
34 ...(categories?.added || []).map((c) => [c]),
35 ...(categories?.removed || []).map((c) => [c]),
36];
37
38/** Every ancestor page a change touches, e.g. `/essentials/`, `/essentials/browsers/`. */
39const ancestorPaths = (crumbs: Crumbs) => {
40 const parts = crumbs.filter(Boolean).map((part) => slugify(part as string));
41 return parts.map((_, index) => `/${parts.slice(0, index + 1).join('/')}/`);
42};
43
44/** Maps each listing page to the date its content last changed, for sitemap `lastmod`. */
45export const fetchLastmod = async (): Promise<Record<string, string>> => {
46 const { entries } = await fetchChangelog();
47 const lastmod: Record<string, string> = {};
48 entries.forEach((entry) => {
49 listChanged(entry.changes)
50 .flatMap(ancestorPaths)
51 .forEach((path) => {
52 if (!lastmod[path] || entry.date > lastmod[path]) {
53 lastmod[path] = entry.date;
54 }
55 });
56 });
57 return lastmod;
58};