aboutsummaryrefslogtreecommitdiff
path: root/examples/ssr/src/pages/api/cart.ts
diff options
context:
space:
mode:
authorGravatar github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 2025-06-05 14:25:23 +0000
committerGravatar github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 2025-06-05 14:25:23 +0000
commite586d7d704d475afe3373a1de6ae20d504f79d6d (patch)
tree7e3fa24807cebd48a86bd40f866d792181191ee9 /examples/ssr/src/pages/api/cart.ts
downloadastro-latest.tar.gz
astro-latest.tar.zst
astro-latest.zip
Sync from a8e1c0a7402940e0fc5beef669522b315052df1blatest
Diffstat (limited to 'examples/ssr/src/pages/api/cart.ts')
-rw-r--r--examples/ssr/src/pages/api/cart.ts38
1 files changed, 38 insertions, 0 deletions
diff --git a/examples/ssr/src/pages/api/cart.ts b/examples/ssr/src/pages/api/cart.ts
new file mode 100644
index 000000000..8d64ec7d8
--- /dev/null
+++ b/examples/ssr/src/pages/api/cart.ts
@@ -0,0 +1,38 @@
+import type { 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 Response.json({ items: [] });
+ }
+ let items = userCartItems.get(userId);
+ let array = Array.from(items.values());
+
+ return Response.json({ 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 Response.json({ ok: true });
+}