diff options
author | 2022-03-16 12:16:21 -0400 | |
---|---|---|
committer | 2022-03-16 12:16:21 -0400 | |
commit | 4c25a1c2eacf897427a7d6dac3bf476ef56799de (patch) | |
tree | db1d341557694e17a07027ebea160c89bad4813d /examples/ssr/src/api.ts | |
parent | 8f13b3d4068f0f017186fbc2dbd33a1427768ea4 (diff) | |
download | astro-4c25a1c2eacf897427a7d6dac3bf476ef56799de.tar.gz astro-4c25a1c2eacf897427a7d6dac3bf476ef56799de.tar.zst astro-4c25a1c2eacf897427a7d6dac3bf476ef56799de.zip |
Implements redirects, headers for SSR (#2798)
* Implements redirects, headers for SSR
* Move away from an explicit Request
* Properly handle endpoint routes in the build
* chore(lint): ESLint fix
* Update based on review comments
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Diffstat (limited to 'examples/ssr/src/api.ts')
-rw-r--r-- | examples/ssr/src/api.ts | 51 |
1 files changed, 47 insertions, 4 deletions
diff --git a/examples/ssr/src/api.ts b/examples/ssr/src/api.ts index 59619ade6..b71990f3f 100644 --- a/examples/ssr/src/api.ts +++ b/examples/ssr/src/api.ts @@ -5,12 +5,25 @@ interface Product { image: string; } -//let origin: string; -const { mode } = import.meta.env; -const origin = mode === 'develepment' ? `http://localhost:3000` : `http://localhost:8085`; +interface User { + id: number; +} + +interface Cart { + items: Array<{ + id: number; + name: string; + count: number; + }>; +} + +const { MODE } = import.meta.env; +const origin = MODE === 'development' ? `http://127.0.0.1:3000` : `http://127.0.0.1:8085`; async function get<T>(endpoint: string, cb: (response: Response) => Promise<T>): Promise<T> { - const response = await fetch(`${origin}${endpoint}`); + const response = await fetch(`${origin}${endpoint}`, { + credentials: 'same-origin' + }); if (!response.ok) { // TODO make this better... return null; @@ -31,3 +44,33 @@ export async function getProduct(id: number): Promise<Product> { return product; }); } + +export async function getUser(): Promise<User> { + return get<User>(`/api/user`, async response => { + const user: User = await response.json(); + return user; + }); +} + +export async function getCart(): Promise<Cart> { + return get<Cart>(`/api/cart`, async response => { + const cart: Cart = await response.json(); + return cart; + }); +} + +export async function addToUserCart(id: number | string, name: string): Promise<void> { + await fetch(`${origin}/api/add-to-cart`, { + credentials: 'same-origin', + method: 'POST', + mode: 'no-cors', + headers: { + 'Content-Type': 'application/json', + 'Cache': 'no-cache' + }, + body: JSON.stringify({ + id, + name + }) + }); +} |