Skip to content

Commit 1ea3221

Browse files
committed
refactor(api): simplify 'years' endpoint
1 parent 09ea878 commit 1ea3221

File tree

2 files changed

+22
-33
lines changed

2 files changed

+22
-33
lines changed

src/pages/api/v1/years/[year].json.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,21 @@ const quoteRecords = await getCollection("quoteRecords");
1111
const quoteDates = new Set(
1212
quoteRecords.flatMap((quoteRecord) => Object.keys(quoteRecord.data)),
1313
);
14-
const quoteYears = new Set(
14+
export const quoteYears = new Set(
1515
[...quoteDates].map((date) => new Date(date).getUTCFullYear()),
1616
);
1717

18-
export const getStaticPaths = (() => {
19-
const quotesByYearBySymbol = new Map(
20-
quoteRecords.map((quoteRecord) => {
21-
const quotes = Object.entries(quoteRecord.data);
22-
return [
23-
quoteRecord.id,
24-
Map.groupBy(quotes, ([date]) => new Date(date).getUTCFullYear()),
25-
];
26-
}),
27-
);
18+
export const quotesByYearBySymbol = new Map(
19+
quoteRecords.map((quoteRecord) => {
20+
const quotes = Object.entries(quoteRecord.data);
21+
return [
22+
quoteRecord.id,
23+
Map.groupBy(quotes, ([date]) => new Date(date).getUTCFullYear()),
24+
];
25+
}),
26+
);
2827

28+
export const getStaticPaths = (() => {
2929
return [...quoteYears].map((year) => ({
3030
params: { year: year.toString() },
3131
props: Object.fromEntries(

src/pages/api/v1/years/index.json.ts

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,15 @@
11
import type { APIRoute } from "astro";
2-
import { getCollection } from "astro:content";
32

4-
const quoteRecords = await getCollection("quoteRecords");
5-
6-
const symbolsByYear = new Map<number, string[]>();
7-
for (const quoteRecord of quoteRecords) {
8-
const years = [
9-
...new Set(
10-
Object.keys(quoteRecord.data).map((date) =>
11-
new Date(date).getUTCFullYear(),
12-
),
13-
),
14-
];
15-
for (const year of years) {
16-
let symbols = symbolsByYear.get(year);
17-
if (symbols == null) {
18-
symbols = [];
19-
symbolsByYear.set(year, symbols);
20-
}
21-
symbols.push(quoteRecord.id);
22-
}
23-
}
3+
import { quoteYears, quotesByYearBySymbol } from "./[year].json";
244

255
export const GET: APIRoute = () =>
26-
Response.json(Object.fromEntries(symbolsByYear));
6+
Response.json(
7+
Object.fromEntries(
8+
[...quoteYears].map((year) => [
9+
year,
10+
[...quotesByYearBySymbol]
11+
.filter(([, quotesByYear]) => quotesByYear.has(year))
12+
.map(([symbol]) => symbol),
13+
]),
14+
),
15+
);

0 commit comments

Comments
 (0)