mirror of
https://gitlab.com/wheres-the-tp/ui-mobile.git
synced 2026-01-25 05:54:56 -06:00
87 lines
2.2 KiB
JavaScript
87 lines
2.2 KiB
JavaScript
import mapPropsStream from 'recompose/mapPropsStream';
|
|
import CreateProduct$, { emitter as emitCreateItemState } from '../streams/CreateProductStream';
|
|
import { emitter as emitProductsState } from '../streams/ProductsStream';
|
|
import { createProduct } from '../apis/ProductsApi';
|
|
import ProductRecord, { createProduct as buildProduct } from '../records/ProductRecord';
|
|
import Snackbar from 'react-native-snackbar';
|
|
|
|
export const withCreateProductState = mapPropsStream(props$ => {
|
|
return props$.combineLatest(CreateProduct$, (props, state) => {
|
|
const { product, loading, error } = state;
|
|
|
|
const setProduct = (product: ProductRecord) => emitCreateItemState({ ...state, product });
|
|
const setLoading = (loading: boolean) => emitCreateItemState({ ...state, loading });
|
|
const setError = (error: Error) => emitCreateItemState({ ...state, error });
|
|
|
|
const saveProduct = async () => {
|
|
try {
|
|
// insert new item into db and cast it into ProductRecord
|
|
const newItem = buildProduct(await createProduct(product));
|
|
|
|
Snackbar.show({
|
|
title: product.name + ' added',
|
|
backgroundColor: 'black',
|
|
color: 'white',
|
|
});
|
|
|
|
// notify food items state of new item
|
|
emitProductsState(newItem);
|
|
|
|
// clear the create item form to default empty record
|
|
setProduct(new ProductRecord());
|
|
|
|
// allow caller to see what was created
|
|
return newItem;
|
|
} catch (err) {
|
|
const error = formatError(err);
|
|
|
|
Snackbar.show({
|
|
title: error,
|
|
duration: Snackbar.LENGTH_LONG,
|
|
backgroundColor: 'black',
|
|
color: 'white',
|
|
});
|
|
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
return {
|
|
...props,
|
|
product,
|
|
loading,
|
|
error,
|
|
setProduct,
|
|
saveProduct,
|
|
setLoading,
|
|
setError,
|
|
};
|
|
});
|
|
});
|
|
|
|
function getNameForKey(key) {
|
|
switch (key) {
|
|
case 'name':
|
|
return 'Name';
|
|
case 'placeId':
|
|
return 'Place';
|
|
case 'category':
|
|
return 'Category';
|
|
case 'quantity':
|
|
return 'Quantity';
|
|
case 'latitude':
|
|
case 'longitude':
|
|
default:
|
|
return '';
|
|
}
|
|
}
|
|
|
|
function formatError({ message } = {}) {
|
|
try {
|
|
const msgObj = JSON.parse(message);
|
|
if (msgObj.missingkeys) {
|
|
return `Please fill in ${msgObj.missingkeys.map(getNameForKey).join(', ')}`;
|
|
}
|
|
} catch (err) {} //eslint-disable-line
|
|
return message;
|
|
}
|