import { pathOr, map, nth } from 'ramda'; import ProductRecord from '../records/ProductRecord'; import AuthManager from '../AuthManager'; import { addImage } from './ImagesApi'; import { fetchRequest } from './FetchApi'; import debounce from '../helpers/debounce'; export type ProductsFilter = { radius?: number, }; export type RawProduct = { id: string, name: string, placeid: string, category: string, images: string, thumbimage: string, latitude: number, longitude: number, distance: number, lastupdated: number, }; export type ProductsForLocation = { orderby: string, filter: ProductsFilter, products: ?Array, }; export const getProducts = debounce(async ({ filter }) => { const { search } = filter; if (!search) { return { products: [], loading: false, error: null, }; } try { const { products } = await fetchRequest({ endpoint: `/products/${encodeURIComponent(search)}`, }); return { products, loading: false, error: null, }; } catch (error) { console.error(error); // eslint-disable-line no-console return { orderby: 'distance', filter: {}, products: [], loading: false, error: error, }; } }, 500); export const createProduct = async (product: ProductRecord) => { if (!AuthManager.user) { throw new Error('You must be logged in to create food items'); } const username = AuthManager.user.name; const res = await fetchRequest({ endpoint: '/addproduct', method: 'POST', body: product, }); const addImageUri = (imageUri: string) => addImage({ productId: res.id, imageUri, username }); const images = await Promise.all(map(addImageUri, product.images.toArray())); const thumbimage = pathOr('', ['url'], nth(0, images)); return { ...res, images, thumbimage, }; };