-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathProducts.ts
More file actions
54 lines (43 loc) · 1.28 KB
/
Products.ts
File metadata and controls
54 lines (43 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { Product } from '../types/Product';
import { ProductDetails } from '../types/ProductDetails';
const BASE_URL = 'api/products.json';
export function getProducts(): Promise<Product[]> {
return fetch(BASE_URL).then(response => {
if (!response) {
throw new Error('Failed to fetch products');
}
return response.json();
});
}
const fetchFromCategory = (category: string, productId: string) => {
const url = `api/${category}.json`;
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error();
}
return response.json();
})
.then((products: ProductDetails[]) => {
const found = products.find(p => p.id === productId);
if (!found) {
throw new Error();
}
return found;
});
};
export function getProductDetails(productId: string): Promise<ProductDetails> {
return fetchFromCategory('phones', productId)
.catch(() => {
return fetchFromCategory('tablets', productId);
})
.catch(() => {
return fetchFromCategory('accessories', productId);
});
}
export function getSuggestedProducts(): Promise<Product[]> {
return getProducts().then(products => {
const shuffled = [...products].sort(() => 0.5 - Math.random());
return shuffled.slice(0, 8);
});
}