2022-02-14 17:48:52 +00:00
|
|
|
interface Product {
|
|
|
|
id: number;
|
|
|
|
name: string;
|
|
|
|
price: number;
|
|
|
|
image: string;
|
|
|
|
}
|
|
|
|
|
2022-03-16 16:16:21 +00:00
|
|
|
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`;
|
2022-02-14 17:48:52 +00:00
|
|
|
|
|
|
|
async function get<T>(endpoint: string, cb: (response: Response) => Promise<T>): Promise<T> {
|
2022-03-16 16:16:21 +00:00
|
|
|
const response = await fetch(`${origin}${endpoint}`, {
|
2022-03-16 16:17:34 +00:00
|
|
|
credentials: 'same-origin',
|
2022-03-16 16:16:21 +00:00
|
|
|
});
|
2022-02-14 17:50:16 +00:00
|
|
|
if (!response.ok) {
|
2022-02-14 17:48:52 +00:00
|
|
|
// TODO make this better...
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return cb(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getProducts(): Promise<Product[]> {
|
2022-02-14 17:50:16 +00:00
|
|
|
return get<Product[]>('/api/products', async (response) => {
|
2022-02-14 17:48:52 +00:00
|
|
|
const products: Product[] = await response.json();
|
|
|
|
return products;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getProduct(id: number): Promise<Product> {
|
2022-02-14 17:50:16 +00:00
|
|
|
return get<Product>(`/api/products/${id}`, async (response) => {
|
2022-02-14 17:48:52 +00:00
|
|
|
const product: Product = await response.json();
|
|
|
|
return product;
|
|
|
|
});
|
|
|
|
}
|
2022-03-16 16:16:21 +00:00
|
|
|
|
|
|
|
export async function getUser(): Promise<User> {
|
2022-03-16 16:17:34 +00:00
|
|
|
return get<User>(`/api/user`, async (response) => {
|
2022-03-16 16:16:21 +00:00
|
|
|
const user: User = await response.json();
|
|
|
|
return user;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getCart(): Promise<Cart> {
|
2022-03-16 16:17:34 +00:00
|
|
|
return get<Cart>(`/api/cart`, async (response) => {
|
2022-03-16 16:16:21 +00:00
|
|
|
const cart: Cart = await response.json();
|
|
|
|
return cart;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function addToUserCart(id: number | string, name: string): Promise<void> {
|
2022-03-29 12:18:11 +00:00
|
|
|
await fetch(`${origin}/api/cart`, {
|
2022-03-16 16:16:21 +00:00
|
|
|
credentials: 'same-origin',
|
|
|
|
method: 'POST',
|
|
|
|
mode: 'no-cors',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
2022-03-16 16:17:34 +00:00
|
|
|
Cache: 'no-cache',
|
2022-03-16 16:16:21 +00:00
|
|
|
},
|
|
|
|
body: JSON.stringify({
|
|
|
|
id,
|
2022-03-16 16:17:34 +00:00
|
|
|
name,
|
|
|
|
}),
|
2022-03-16 16:16:21 +00:00
|
|
|
});
|
|
|
|
}
|