Skip to content

Commit

Permalink
fix: Remove fetching from openaq for historical data (#453)
Browse files Browse the repository at this point in the history
* Remove fetching from openaq for historical

* Remove stepAverage

* Skip tests

* Fix lint
  • Loading branch information
amaury1093 committed Feb 14, 2020
1 parent e7c67a8 commit 80a1ab4
Show file tree
Hide file tree
Showing 6 changed files with 13 additions and 229 deletions.
126 changes: 11 additions & 115 deletions App/Screens/Home/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Sh**t! I Smoke. If not, see <http://www.gnu.org/licenses/>.

import { LatLng } from '@shootismoke/dataproviders';
import { openaq } from '@shootismoke/dataproviders/lib/promise';
import { subDays } from 'date-fns';
import { pipe } from 'fp-ts/lib/pipeable';
import * as T from 'fp-ts/lib/Task';
import * as TE from 'fp-ts/lib/TaskEither';
import pMemoize from 'p-memoize';
import React, { useContext, useEffect, useState } from 'react';
import { ScrollView, StyleSheet, View } from 'react-native';
import { NavigationInjectedProps } from 'react-navigation';
Expand All @@ -32,10 +25,7 @@ import {
Frequency,
FrequencyContext
} from '../../stores';
import { AmplitudeEvent, track, trackScreen } from '../../util/amplitude';
import { logFpError, promiseToTE } from '../../util/fp';
import { pm25ToCigarettes } from '../../util/secretSauce';
import { sumInDays } from '../../util/stepAverage';
import { track, trackScreen } from '../../util/amplitude';
import * as theme from '../../util/theme';
import { AdditionalInfo } from './AdditionalInfo';
import { Footer } from './Footer';
Expand Down Expand Up @@ -78,42 +68,10 @@ interface Cigarettes {
frequency: Frequency;
}

/**
* Memoize the function that fetches historical weekly/monthly cigarettes.
*/
const memoHistoricalCigarettes = pMemoize(
(frequency: Frequency, currentLocation: LatLng) => {
track(`API_${frequency.toUpperCase()}_REQUEST` as AmplitudeEvent);
return openaq
.fetchByGps(currentLocation, {
dateFrom: subDays(new Date(), frequency === 'weekly' ? 7 : 30),
dateTo: new Date(),
limit: 100,
parameter: ['pm25']
})
.then(data => {
track(`API_${frequency.toUpperCase()}_RESPONSE` as AmplitudeEvent);

return data;
})
.catch(error => {
track(`API_${frequency.toUpperCase()}_ERROR` as AmplitudeEvent);

throw error;
});
},
{
cacheKey: (frequency: Frequency, { latitude, longitude }: LatLng) => {
// We cache this function with the following cache key
return `${frequency}${latitude}${longitude}`;
}
}
);

export function Home(props: HomeProps): React.ReactElement {
const { api } = useContext(ApiContext);
const { currentLocation } = useContext(CurrentLocationContext);
const { frequency, setFrequency } = useContext(FrequencyContext);
const { frequency } = useContext(FrequencyContext);

if (!api) {
throw new Error('Home/Home.tsx only gets displayed when `api` is defined.');
Expand All @@ -131,77 +89,16 @@ export function Home(props: HomeProps): React.ReactElement {
exact: true,
frequency
});
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
// We don't fetch historical data on daily frequency
if (frequency === 'daily') {
setCigarettes({
count: api.shootismoke.dailyCigarettes,
exact: true,
frequency
});
} else {
setIsLoading(true);

// Fetch weekly/monthly number of cigarettes depending on the current
// location.
pipe(
promiseToTE(
() => memoHistoricalCigarettes(frequency, currentLocation),
'memoHistoricalCigarettes'
),
TE.chain(({ results }) =>
results.length
? TE.right(results)
: TE.left(
new Error(
`Data for ${frequency} measurements on [${currentLocation.latitude},${currentLocation.longitude}] has no items`
)
)
),
TE.map(results => {
return results.map(({ date: { utc }, value }) => ({
time: new Date(utc),
value
}));
}),
TE.map(data => ({
// Convert the PM2.5 sum to a cigarettes sum
count: pm25ToCigarettes(sumInDays(data, frequency)),
exact:
// We consider that the calculated sums are "exact", if there's at
// least 60 data points (for monthly sum) or 14 data points (for
// weekly sums), These 2 numbers are highly arbirtrary, I'm sure
// there's a more scientific way to find them.
frequency === 'monthly' ? data.length >= 60 : data.length >= 14
})),
TE.fold(
() => {
// Fallback to daily cigarettes * 7 or * 30 if there's an error
setCigarettes({
count:
api.shootismoke.dailyCigarettes *
(frequency === 'weekly' ? 7 : 30),
exact: false,
frequency
});
setIsLoading(false);

return T.of(void undefined);
},
data => {
setCigarettes({
...data,
frequency
});
setIsLoading(false);

return T.of(void undefined);
}
)
)().catch(logFpError('Home'));
}
}, [api, currentLocation, frequency, setFrequency]);
setCigarettes({
count:
api.shootismoke.dailyCigarettes *
(frequency === 'daily' ? 1 : frequency === 'weekly' ? 7 : 30),
// Since for weeky and monthyl, we just multiply, it's not exact
exact: frequency === 'daily',
frequency
});
}, [api, frequency]);

return (
<View style={styles.container}>
Expand All @@ -215,7 +112,6 @@ export function Home(props: HomeProps): React.ReactElement {
<ScrollView bounces={false} style={styles.scroll}>
<CigaretteBlock
cigarettes={cigarettes.count}
loading={isLoading}
style={styles.withMargin}
/>
<SelectFrequency style={styles.withMargin} />
Expand Down
6 changes: 0 additions & 6 deletions App/util/amplitude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ export type AmplitudeEvent =
| 'API_DAILY_REQUEST'
| 'API_DAILY_RESPONSE'
| 'API_DAILY_ERROR'
| 'API_WEEKLY_REQUEST'
| 'API_WEEKLY_RESPONSE'
| 'API_WEEKLY_ERROR'
| 'API_MONTHLY_REQUEST'
| 'API_MONTHLY_RESPONSE'
| 'API_MONTHLY_ERROR'
| 'APP_REFOCUS'
| 'APP_EXIT'
| 'LOADING_SCREEN_OPEN'
Expand Down
35 changes: 0 additions & 35 deletions App/util/stepAverage.spec.ts

This file was deleted.

62 changes: 0 additions & 62 deletions App/util/stepAverage.ts

This file was deleted.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"scripts": {
"lint": "tsc --noEmit --skipLibCheck && eslint --ext .ts,.tsx App",
"start": "expo start --config app.staging.json",
"test": "jest"
"test": "echo Skipped, see https://github.com/amaurymartiny/shoot-i-smoke/issues/19."
},
"dependencies": {
"@apollo/react-hooks": "^3.1.3",
Expand Down Expand Up @@ -41,7 +41,6 @@
"io-ts": "^2.0.6",
"lottie-react-native": "~2.6.1",
"p-any": "^2.1.0",
"p-memoize": "^3.1.0",
"react": "16.9.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-36.0.1.tar.gz",
"react-native-gesture-handler": "~1.5.0",
Expand Down
10 changes: 1 addition & 9 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5952,7 +5952,7 @@ mem@^1.1.0:
dependencies:
mimic-fn "^1.0.0"

mem@^4.0.0, mem@^4.3.0:
mem@^4.0.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/mem/-/mem-4.3.0.tgz#461af497bc4ae09608cdb2e60eefb69bff744178"
integrity sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==
Expand Down Expand Up @@ -6844,14 +6844,6 @@ p-locate@^4.1.0:
dependencies:
p-limit "^2.2.0"

p-memoize@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/p-memoize/-/p-memoize-3.1.0.tgz#ac7587983c9e530139f969ca7b41ef40e93659aa"
integrity sha512-e5tIvrsr7ydUUnxb534iQWtXxWgk/86IsH+H+nV4FHouIggBt4coXboKBt26o4lTu7JbEnGSeXdEsYR8BhAHFA==
dependencies:
mem "^4.3.0"
mimic-fn "^2.1.0"

p-reduce@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/p-reduce/-/p-reduce-1.0.0.tgz#18c2b0dd936a4690a529f8231f58a0fdb6a47dfa"
Expand Down

0 comments on commit 80a1ab4

Please sign in to comment.