diff options
author | 2025-06-05 14:25:23 +0000 | |
---|---|---|
committer | 2025-06-05 14:25:23 +0000 | |
commit | e586d7d704d475afe3373a1de6ae20d504f79d6d (patch) | |
tree | 7e3fa24807cebd48a86bd40f866d792181191ee9 /examples/ssr/src/pages/api/cart.ts | |
download | astro-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.ts | 38 |
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 }); +} |