-
Notifications
You must be signed in to change notification settings - Fork 417
Expand file tree
/
Copy pathapi.ts
More file actions
57 lines (50 loc) · 1.48 KB
/
api.ts
File metadata and controls
57 lines (50 loc) · 1.48 KB
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
import { query } from "@solidjs/router";
import { StoryDefinition, StoryTypes, UserDefinition } from "~/types";
const story = (path: string) => `https://node-hnapi.herokuapp.com/${path}`;
const user = (path: string) => `https://hacker-news.firebaseio.com/v0/${path}.json`;
async function fetchAPI(path: string) {
const url = path.startsWith("user") ? user(path) : story(path);
const headers: Record<string, string> = { "User-Agent": "chrome" };
try {
let response = await fetch(url, { headers });
let text = await response.text();
try {
if (text === null) {
return { error: "Not found" };
}
return JSON.parse(text);
} catch (e) {
console.error(`Received from API: ${text}`);
console.error(e);
return { error: e };
}
} catch (error) {
return { error };
}
}
const mapStories = {
top: "news",
new: "newest",
show: "show",
ask: "ask",
job: "jobs",
} as const;
export const getStories = query(
async (type: StoryTypes, page: number): Promise<StoryDefinition[]> => {
"use server";
const storyType = mapStories[type];
if (!storyType) {
return [];
}
return fetchAPI(`${mapStories[type]}?page=${page}`);
},
"stories",
);
export const getStory = query(async (id: string): Promise<StoryDefinition> => {
"use server";
return fetchAPI(`item/${id}`);
}, "story");
export const getUser = query(async (id: string): Promise<UserDefinition> => {
"use server";
return fetchAPI(`user/${id}`);
}, "user");