aboutsummaryrefslogtreecommitdiff
path: root/examples/ssr/src/api.ts
blob: 2d10a85f9efc1f2abc53e16d1074a1bf8c1f1b58 (plain) (blame)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
export interface Product {
	id: number;
	name: string;
	price: number;
	image: string;
}

interface User {
	id: number;
}

interface Cart {
	items: Array<{
		id: number;
		name: string;
		count: number;
	}>;
}

async function getJson<T>(
	incomingReq: Request,
	endpoint: string,
): Promise<T> {
	const origin = new URL(incomingReq.url).origin;
	try {
		const response = await fetch(`${origin}${endpoint}`, {
			credentials: 'same-origin',
			headers: incomingReq.headers,
		});
		if (!response.ok) {
			throw new Error(`GET ${endpoint} failed: ${response.statusText}`);
		}
		return response.json() as Promise<T>;
	} catch (error) {
		if (error instanceof DOMException || error instanceof TypeError) {
			throw new Error(`GET ${endpoint} failed: ${error.message}`);
		}
		throw error;
	}
}

export async function getProducts(incomingReq: Request): Promise<Product[]> {
	return getJson<Product[]>(incomingReq, '/api/products');
}

export async function getProduct(incomingReq: Request, id: number): Promise<Product> {
	return getJson<Product>(incomingReq, `/api/products/${id}`);
}

export async function getUser(incomingReq: Request): Promise<User> {
	return getJson<User>(incomingReq, `/api/user`);
}

export async function getCart(incomingReq: Request): Promise<Cart> {
	return getJson<Cart>(incomingReq, `/api/cart`);
}

export async function addToUserCart(id: number | string, name: string): Promise<void> {
	await fetch(`${location.origin}/api/cart`, {
		credentials: 'same-origin',
		method: 'POST',
		mode: 'no-cors',
		headers: {
			'Content-Type': 'application/json',
			Cache: 'no-cache',
		},
		body: JSON.stringify({
			id,
			name,
		}),
	});
}