Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

hn-api.ts

47 lines1.1 KB

1export interface HnItem {
2 id: number;
3 type?: string;
4 title?: string;
5 url?: string;
6 by?: string;
7 time?: number;
8 score?: number;
9 descendants?: number;
10 dead?: boolean;
11 deleted?: boolean;
12 kids?: number[];
13 parent?: number;
14 text?: string;
16​
17const API = "https://hacker-news.firebaseio.com/v0";
18export async function readHn<T>(
19 path: string,
20 signal?: AbortSignal,
21): Promise<T> {
22 const response = await fetch(`${API}/${path}.json`, {
23 cache: "no-store",
24 signal: signal
25 ? AbortSignal.any([signal, AbortSignal.timeout(15000)])
26 : AbortSignal.timeout(15000),
27 });
28 if (!response.ok) throw new Error(`HN source returned ${response.status}`);
29 return response.json() as Promise<T>;
31export async function mapLimit<T, U>(
32 values: T[],
33 limit: number,
34 fn: (value: T) => Promise<U>,
35): Promise<U[]> {
36 const result: U[] = new Array(values.length);
37 let cursor = 0;
38 await Promise.all(
39 Array.from({ length: Math.min(limit, values.length) }, async () => {
40 while (cursor < values.length) {
41 const index = cursor++;
42 result[index] = await fn(values[index]);
43 }
44 }),
45 );
46 return result;