aretherecookies-mobile/js/apis/FoodItemsApi.js

100 lines
1.9 KiB
JavaScript
Raw Normal View History

2017-08-27 14:29:37 -05:00
// @flow
2017-10-22 12:38:05 -05:00
import { memoize } from 'ramda';
2017-11-11 20:15:19 -06:00
import FilterRecord from '../records/FilterRecord';
import FoodItemRecord from '../records/FoodItemRecord';
2018-03-10 11:54:12 -06:00
import AuthManager from '../AuthManager';
2018-04-08 10:54:29 -05:00
import { map, path, nth } from 'ramda';
import { addImage } from './ImagesApi';
import { fetchRequest } from './FetchApi';
2017-10-29 20:18:33 -05:00
2017-10-22 12:38:05 -05:00
export type FoodItemsFilter = {
radius?: number,
};
export type RawFoodItem = {
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,
lastupdated: number,
2017-10-22 12:38:05 -05:00
};
2017-08-27 14:29:37 -05:00
2017-10-22 12:38:05 -05:00
export type FoodItemsForLocation = {
orderby: string,
filter: FoodItemsFilter,
fooditems: ?Array<RawFoodItem>,
2017-08-27 14:29:37 -05:00
};
2017-10-22 12:38:05 -05:00
export const getFoodItems = memoize(
async ({
loc,
filter,
}: {
loc: Position,
filter: FilterRecord,
}): Promise<FoodItemsForLocation> => {
const {
coords: { latitude: lat, longitude: lng },
} = loc;
const { orderby, categories, radius } = filter;
2017-11-11 20:15:19 -06:00
try {
return fetchRequest({
endpoint: '/fooditems',
method: 'POST',
body: {
lat,
lng,
orderby,
filter: {
...(categories ? { categories } : {}),
radius,
},
},
}).then(json => ({
...json,
loading: false,
error: null,
}));
} catch (error) {
2018-04-08 10:54:29 -05:00
console.log(error); // eslint-disable-line no-console
return {
orderby: 'distance',
filter: {},
fooditems: [],
2017-10-22 12:38:05 -05:00
loading: false,
error: error,
};
}
2017-10-22 12:38:05 -05:00
}
);
export const createFoodItem = async (foodItem: FoodItemRecord) => {
const res = await fetchRequest({
endpoint: '/addfooditem',
method: 'POST',
body: foodItem,
});
2018-03-10 11:54:12 -06:00
if (!AuthManager.user) {
return;
}
const username = AuthManager.user.name;
2018-04-08 10:54:29 -05:00
const addImageUri = (imageUri: string) => addImage({ foodItemId: res.id, imageUri, username });
const images = map(path(['url']), await Promise.all(map(addImageUri, foodItem.images.toArray())));
return {
...res,
images,
2018-04-08 10:54:29 -05:00
thumbimage: nth(0, images),
};
};