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 | |
download | astro-latest.tar.gz astro-latest.tar.zst astro-latest.zip |
Sync from a8e1c0a7402940e0fc5beef669522b315052df1blatest
Diffstat (limited to 'examples/ssr/src/pages/api')
-rw-r--r-- | examples/ssr/src/pages/api/cart.ts | 38 | ||||
-rw-r--r-- | examples/ssr/src/pages/api/products.ts | 5 | ||||
-rw-r--r-- | examples/ssr/src/pages/api/products/[id].ts | 16 |
3 files changed, 59 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 }); +} diff --git a/examples/ssr/src/pages/api/products.ts b/examples/ssr/src/pages/api/products.ts new file mode 100644 index 000000000..8bf02a03d --- /dev/null +++ b/examples/ssr/src/pages/api/products.ts @@ -0,0 +1,5 @@ +import { products } from '../../models/db'; + +export function GET() { + return new Response(JSON.stringify(products)); +} diff --git a/examples/ssr/src/pages/api/products/[id].ts b/examples/ssr/src/pages/api/products/[id].ts new file mode 100644 index 000000000..f0f6fa89f --- /dev/null +++ b/examples/ssr/src/pages/api/products/[id].ts @@ -0,0 +1,16 @@ +import { productMap } from '../../../models/db'; +import type { APIContext } from 'astro'; + +export function GET({ params }: APIContext) { + const id = Number(params.id); + if (productMap.has(id)) { + const product = productMap.get(id); + + return new Response(JSON.stringify(product)); + } else { + return new Response(null, { + status: 400, + statusText: 'Not found', + }); + } +} |