Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sessiontoken and sparse fields #867

Merged
merged 4 commits into from
Jul 19, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ way to update this template, but currently, we follow a pattern:
---

## Upcoming version

* [change] Use sessionTokens and fields for Autocomplete calls to Google Maps.
This is a reaction to pricing change of Google Maps APIs.
[#867](https://github.com/sharetribe/flex-template-web/pull/867)
* [change] Change TransactionPage state management in loadData.
[#863](https://github.com/sharetribe/flex-template-web/pull/863), [#865](https://github.com/sharetribe/flex-template-web/pull/865) & [#866](https://github.com/sharetribe/flex-template-web/pull/866)
* [fix] Fix submit button state on contact details page.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ class LocationAutocompleteInput extends Component {
// Ref to the input element.
this.input = null;

// Current sessionToken used to combine autocomplete calls with place details call
// This reduces Google Maps pricing.
this.autocompleteSessionToken = null;

this.changeHighlight = this.changeHighlight.bind(this);
this.selectItem = this.selectItem.bind(this);
this.selectItemIfNoneSelected = this.selectItemIfNoneSelected.bind(this);
Expand Down Expand Up @@ -213,6 +217,7 @@ class LocationAutocompleteInput extends Component {
this.setState({ highlightedIndex: -1 });

if (!newValue) {
this.autocompleteSessionToken = null;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the token need to be cleared out when user clears input when the place details have not been retrieved? E.g. input "Hel" -> delete all -> input "Espoo" -> click the item? Is this one or two sessions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bladealslayer that's what I understood from docs, but I'm not sure. Should be asked from Google guys. Those docs just say that if the same session token is used in several sessions/occasions, all the calls are handled individually -> it cancels the price reduction of the token.

I assume that there's an undisclosed lifetime on those tokens - but since it's undisclosed, I assume that the desired behavior is that one character search "sequence" group is one session: "h", "he", "hel" -> "Helsinki".

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://developers.google.com/maps/documentation/javascript/places-autocomplete#session_tokens
"Warning: Be sure to pass a unique session token for each new session. Using the same token for more than one session will result in each request being billed individually. Note that the Autocomplete Widget handles sessions automatically (you don't need to do anything additional)."

// No need to fetch predictions on empty input
return;
}
Expand Down Expand Up @@ -266,14 +271,19 @@ class LocationAutocompleteInput extends Component {
selectedPlace: null,
});

getPlaceDetails(placeId)
this.autocompleteSessionToken =
this.autocompleteSessionToken || new window.google.maps.places.AutocompleteSessionToken();
const sessionToken = this.autocompleteSessionToken;

getPlaceDetails(placeId, sessionToken)
.then(place => {
this.props.input.onChange({
search: prediction.description,
predictions: [],
selectedPlaceId: placeId,
selectedPlace: place,
});
this.autocompleteSessionToken = null;
})
.catch(e => {
// eslint-disable-next-line no-console
Expand All @@ -298,7 +308,12 @@ class LocationAutocompleteInput extends Component {
throw new Error('Google Maps API must be loaded for LocationAutocompleteInput');
}
const onChange = this.props.input.onChange;
getPlacePredictions(search)

this.autocompleteSessionToken =
this.autocompleteSessionToken || new window.google.maps.places.AutocompleteSessionToken();
const sessionToken = this.autocompleteSessionToken;

getPlacePredictions(search, sessionToken)
.then(results => {
const { search: currentSearch } = currentValue(this.props);

Expand Down
15 changes: 11 additions & 4 deletions src/util/googleMaps.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,21 @@ const placeCountry = place => {
*
* @param {String} placeId - ID for a place received from the
* autocomplete service
* @param {String} sessionToken - token to tie different autocomplete character searches together
* with getPlaceDetails call
*
* @return {Promise<util.propTypes.place>} Promise that
* resolves to the detailed place, rejects if the request failed
*/
export const getPlaceDetails = placeId =>
export const getPlaceDetails = (placeId, sessionToken) =>
new Promise((resolve, reject) => {
const serviceStatus = window.google.maps.places.PlacesServiceStatus;
const el = document.createElement('div');
const service = new window.google.maps.places.PlacesService(el);
const fields = ['address_component', 'formatted_address', 'geometry', 'place_id'];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't the place_id known already?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but it doesn't hurt to have that returned also (it's part of the basic fields => same pricing). Anyway, id's included to the return object makes them easier to be reused in Redux store if that kind of feature is needed.

const sessionTokenMaybe = sessionToken ? { sessionToken } : {};

service.getDetails({ placeId }, (place, status) => {
service.getDetails({ placeId, fields, ...sessionTokenMaybe }, (place, status) => {
if (status !== serviceStatus.OK) {
reject(
new Error(`Could not get details for place id "${placeId}", error status was "${status}"`)
Expand All @@ -71,16 +75,19 @@ const predictionSuccessful = status => {
* Get place predictions for the given search
*
* @param {String} search - place name or address to search
* @param {String} sessionToken - token to tie different autocomplete character searches together
* with getPlaceDetails call
*
* @return {Promise<{ search, predictions[] }>} - Promise of an object
* with the original search query and an array of
* `google.maps.places.AutocompletePrediction` objects
*/
export const getPlacePredictions = search =>
export const getPlacePredictions = (search, sessionToken) =>
new Promise((resolve, reject) => {
const service = new window.google.maps.places.AutocompleteService();
const sessionTokenMaybe = sessionToken ? { sessionToken } : {};

service.getPlacePredictions({ input: search }, (predictions, status) => {
service.getPlacePredictions({ input: search, ...sessionTokenMaybe }, (predictions, status) => {
if (!predictionSuccessful(status)) {
reject(new Error(`Prediction service status not OK: ${status}`));
} else {
Expand Down