summaryrefslogtreecommitdiff
path: root/examples/ssr/src/pages/api/cart.ts
blob: cc6ba231b178346046aa98c3a217f161f3340496 (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
import { APIContext } from 'astro';
import { userCartItems } from '../../models/session';

export function GET({ cookies }: APIContext) {
	let userId = cookies.get('user-id').value;

	if (!userId || !userCartItems.has(userId)) {
		return {
			body: JSON.stringify({ items: [] }),
		};
	}
	let items = userCartItems.get(userId);
	let array = Array.from(items.values());

	return new Response(JSON.stringify({ items: array }));
}

interface AddToCartItem {
	id: number;
	name: string;
}

export async function POST({ cookies, request }: APIContext) {
	const item: AddToCartItem = await request.json();

	let userId = cookies.get('user-id').value;

	if (!userCartItems.has(userId)) {
		userCartItems.set(userId, new Map());
	}

	let cart = userCartItems.get(userId);
	if (cart.has(item.id)) {
		cart.get(item.id).count++;
	} else {
		cart.set(item.id, { id: item.id, name: item.name, count: 1 });
	}

	return new Response(
		JSON.stringify({
			ok: true,
		})
	);
}