aretherecookies-mobile/js/apis/ProductsApi.js

89 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2020-04-17 22:50:23 -05:00
import { pathOr, map, nth } from 'ramda';
import ProductRecord from '../records/ProductRecord';
2020-04-03 22:21:26 -05:00
import AuthManager from '../AuthManager';
import { addImage } from './ImagesApi';
import { fetchRequest } from './FetchApi';
2020-04-05 19:26:25 -05:00
import debounce from '../helpers/debounce';
2017-10-29 20:18:33 -05:00
2020-04-17 22:50:23 -05:00
export type ProductsFilter = {
2020-04-03 22:21:26 -05:00
radius?: number,
2017-10-22 12:38:05 -05:00
};
2020-04-17 22:50:23 -05:00
export type RawProduct = {
2017-10-22 12:38:05 -05:00
id: string,
name: string,
2018-04-08 10:54:29 -05:00
placeid: string,
2017-10-22 12:38:05 -05:00
category: string,
images: string,
thumbimage: string,
latitude: number,
longitude: number,
distance: number,
2020-04-03 22:21:26 -05:00
lastupdated: number,
2017-10-22 12:38:05 -05:00
};
2017-08-27 14:29:37 -05:00
2020-04-17 22:50:23 -05:00
export type ProductsForLocation = {
2017-10-22 12:38:05 -05:00
orderby: string,
2020-04-17 22:50:23 -05:00
filter: ProductsFilter,
products: ?Array<RawProduct>,
2017-08-27 14:29:37 -05:00
};
2017-10-22 12:38:05 -05:00
2020-04-17 22:50:23 -05:00
export const getProducts = debounce(async ({ filter }) => {
const { search } = filter;
2017-11-11 20:15:19 -06:00
if (!search) {
return {
2020-04-17 22:50:23 -05:00
products: [],
loading: false,
error: null,
};
}
try {
2020-04-17 22:50:23 -05:00
const { products } = await fetchRequest({
endpoint: `/products/${encodeURIComponent(search)}`,
});
return {
2020-04-17 22:50:23 -05:00
products,
loading: false,
error: null,
};
} catch (error) {
console.error(error); // eslint-disable-line no-console
return {
orderby: 'distance',
filter: {},
2020-04-17 22:50:23 -05:00
products: [],
loading: false,
error: error,
};
}
}, 500);
2020-04-17 22:50:23 -05:00
export const createProduct = async (product: ProductRecord) => {
2019-03-02 10:37:53 -06:00
if (!AuthManager.user) {
2020-04-03 22:21:26 -05:00
throw new Error('You must be logged in to create food items');
2019-03-02 10:37:53 -06:00
}
const username = AuthManager.user.name;
const res = await fetchRequest({
2020-04-17 22:50:23 -05:00
endpoint: '/addproduct',
2020-04-03 22:21:26 -05:00
method: 'POST',
2020-04-17 22:50:23 -05:00
body: product,
});
2020-04-17 22:50:23 -05:00
const addImageUri = (imageUri: string) => addImage({ productId: res.id, imageUri, username });
2018-04-08 10:54:29 -05:00
2020-04-17 22:50:23 -05:00
const images = await Promise.all(map(addImageUri, product.images.toArray()));
const thumbimage = pathOr('', ['url'], nth(0, images));
return {
...res,
images,
thumbimage,
};
};