aretherecookies-mobile/js/apis/FoodItemsApi.js
2019-09-21 15:45:07 +00:00

95 lines
2 KiB
JavaScript

// @flow
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";
export type FoodItemsFilter = {
radius?: number
};
export type RawFoodItem = {
id: string,
name: string,
placeid: string,
category: string,
images: string,
thumbimage: string,
latitude: number,
longitude: number,
distance: number,
lastupdated: number
};
export type FoodItemsForLocation = {
orderby: string,
filter: FoodItemsFilter,
fooditems: ?Array<RawFoodItem>
};
export const getFoodItems = memoizeWith(
identity,
async ({ loc, filter }: { loc: Position, filter: FilterRecord }): Promise<FoodItemsForLocation> => {
const {
coords: { latitude: lat, longitude: lng }
} = loc;
const { orderby, categories, radius, search } = filter;
try {
return fetchRequest({
endpoint: "/fooditems",
method: "POST",
body: {
lat,
lng,
orderby,
filter: {
...(categories ? { categories } : {}),
radius,
search
}
}
}).then(json => ({
...json,
loading: false,
error: null
}));
} catch (error) {
console.error(error); // eslint-disable-line no-console
return {
orderby: "distance",
filter: {},
fooditems: [],
loading: false,
error: error
};
}
}
);
export const createFoodItem = async (foodItem: FoodItemRecord) => {
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: "/addfooditem",
method: "POST",
body: foodItem
});
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,
thumbimage: nth(0, images)
};
};