Skip to content

Commit

Permalink
refactor(api): simplify 'years' endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
kripod committed Apr 17, 2024
1 parent 09ea878 commit 1ea3221
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 33 deletions.
22 changes: 11 additions & 11 deletions src/pages/api/v1/years/[year].json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,21 @@ const quoteRecords = await getCollection("quoteRecords");
const quoteDates = new Set(
quoteRecords.flatMap((quoteRecord) => Object.keys(quoteRecord.data)),
);
const quoteYears = new Set(
export const quoteYears = new Set(
[...quoteDates].map((date) => new Date(date).getUTCFullYear()),
);

export const getStaticPaths = (() => {
const quotesByYearBySymbol = new Map(
quoteRecords.map((quoteRecord) => {
const quotes = Object.entries(quoteRecord.data);
return [
quoteRecord.id,
Map.groupBy(quotes, ([date]) => new Date(date).getUTCFullYear()),
];
}),
);
export const quotesByYearBySymbol = new Map(
quoteRecords.map((quoteRecord) => {
const quotes = Object.entries(quoteRecord.data);
return [
quoteRecord.id,
Map.groupBy(quotes, ([date]) => new Date(date).getUTCFullYear()),
];
}),
);

export const getStaticPaths = (() => {
return [...quoteYears].map((year) => ({
params: { year: year.toString() },
props: Object.fromEntries(
Expand Down
33 changes: 11 additions & 22 deletions src/pages/api/v1/years/index.json.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,15 @@
import type { APIRoute } from "astro";
import { getCollection } from "astro:content";

const quoteRecords = await getCollection("quoteRecords");

const symbolsByYear = new Map<number, string[]>();
for (const quoteRecord of quoteRecords) {
const years = [
...new Set(
Object.keys(quoteRecord.data).map((date) =>
new Date(date).getUTCFullYear(),
),
),
];
for (const year of years) {
let symbols = symbolsByYear.get(year);
if (symbols == null) {
symbols = [];
symbolsByYear.set(year, symbols);
}
symbols.push(quoteRecord.id);
}
}
import { quoteYears, quotesByYearBySymbol } from "./[year].json";

export const GET: APIRoute = () =>
Response.json(Object.fromEntries(symbolsByYear));
Response.json(
Object.fromEntries(
[...quoteYears].map((year) => [
year,
[...quotesByYearBySymbol]
.filter(([, quotesByYear]) => quotesByYear.has(year))
.map(([symbol]) => symbol),
]),
),
);

0 comments on commit 1ea3221

Please sign in to comment.