aretherecookies-mobile/js/apis/FoodItemsApi.js

96 lines
2 KiB
JavaScript
Raw Normal View History

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