aboutsummaryrefslogtreecommitdiff
path: root/examples/ssr/src/api.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/api.ts
downloadastro-latest.tar.gz
astro-latest.tar.zst
astro-latest.zip
Sync from a8e1c0a7402940e0fc5beef669522b315052df1blatest
Diffstat (limited to 'examples/ssr/src/api.ts')
-rw-r--r--examples/ssr/src/api.ts72
1 files changed, 72 insertions, 0 deletions
diff --git a/examples/ssr/src/api.ts b/examples/ssr/src/api.ts
new file mode 100644
index 000000000..2d10a85f9
--- /dev/null
+++ b/examples/ssr/src/api.ts
@@ -0,0 +1,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,
+ }),
+ });
+}