aretherecookies-mobile/js/streams/PlacesStream.js

85 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2020-04-17 22:50:23 -05:00
import { ReplaySubject } from 'rxjs';
import { buildPlaceRecord } from '../records/PlaceRecord';
import { Map } from 'immutable';
2020-04-17 22:50:23 -05:00
import { findNearbyPlaces } from '../apis/GooglePlacesApi';
import { path } from 'ramda';
import { type GooglePlaceObj } from '../records/PlaceRecord';
import { setById } from '../helpers/ImmutableHelpers';
import location$ from './LocationStream';
import filter$ from './FilterStream';
import FilterRecord from '../records/FilterRecord';
2020-04-17 22:50:23 -05:00
// import products$ from './ProductsStream';
import PlaceRecord from '../records/PlaceRecord';
import geodist from 'geodist';
2018-07-08 19:38:54 -05:00
const getGeoDist = begin => end => geodist(begin, end, { exact: true });
2017-03-26 19:38:29 -05:00
const placesSubject = new ReplaySubject();
export function emitter(val?: ?PlaceRecord) {
placesSubject.next(val);
}
2018-07-15 11:28:38 -05:00
filter$.subscribe(() => emitter(null));
2020-04-17 22:50:23 -05:00
// products$
// .mergeMap((products = Map()) => Observable.from(products.toArray()))
// .mergeMap(([productId, product]) => getPlaceDetails(product))
// .map(buildPlaceRecord)
// .subscribe(emitter);
location$
.combineLatest(filter$)
2018-07-21 11:54:04 -05:00
.debounceTime(200)
2018-07-15 11:28:38 -05:00
.mergeMap(([location, filter]: [?Position, FilterRecord]) => {
2018-08-12 09:51:44 -05:00
return findNearbyPlaces({
location,
radius: filter.radius,
search: filter.search,
2018-07-15 11:28:38 -05:00
});
})
.map((val: { location: ?Position, places: ?Array<GooglePlaceObj> }) => {
2018-07-08 19:38:54 -05:00
if (!val) {
return;
}
if (val.error || !val.places) {
console.log(val.error); // eslint-disable-line no-console
return places;
}
2018-07-15 11:28:38 -05:00
const { places } = val;
const coords = path(['location', 'coords'], val) || {};
2018-07-15 11:28:38 -05:00
const getDist = getGeoDist({ lat: coords.latitude, lon: coords.longitude });
2018-07-08 19:38:54 -05:00
return (places || [])
.map((place: GooglePlaceObj) =>
buildPlaceRecord({
...place,
distance: getDist({ lat: place.geometry.location.lat, lon: place.geometry.location.lng }),
})
)
.sort((left, right) => left.distance - right.distance);
})
2018-07-08 19:38:54 -05:00
.subscribe(places => places && places.map(emitter));
2017-10-22 20:00:57 -05:00
2020-04-17 22:50:23 -05:00
export default placesSubject.scan(
(typeToPlace, place) => {
if (!place) {
return typeToPlace;
}
const { placeType } = place;
if (Object.keys(typeToPlace).includes(placeType)) {
return {
...typeToPlace,
[placeType]: [...typeToPlace[placeType], place],
};
}
return typeToPlace;
},
{ HEB: [], WholeFoods: [] }
);