Skip to content

Commit

Permalink
Simplify API caching slightly (closes #1)
Browse files Browse the repository at this point in the history
We can do this now that the API data for each date is populated using a transaction
  • Loading branch information
bmaupin committed Feb 7, 2020
1 parent 734afe3 commit 999f2b9
Showing 1 changed file with 4 additions and 47 deletions.
51 changes: 4 additions & 47 deletions src/helpers/ApiHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,65 +74,22 @@ class ApiHelper {
}

static async _getCache() {
// If there's a cache matching the current year/month, return it
// If there's a cache matching the current year/month, return it in order to avoid calling the API
const currentYearMonthString = ApiHelper._getCurrentYearMonthString();
if (await caches.has(currentYearMonthString)) {
return await caches.open(currentYearMonthString);
}

// If the latest year/month in the API is current and the API is finished syncing,
// delete all old caches and return a new one for the current year/month
// If the latest year/month in the API is current, delete all the old caches before returning the new one
const latestYearMonthString = await ApiHelper._getLatestYearMonthStringFromApi();
if (
latestYearMonthString === currentYearMonthString &&
ApiHelper._isApiFinishedSyncing(currentYearMonthString)
) {
if (latestYearMonthString === currentYearMonthString) {
await ApiHelper._deleteAllCaches();
return await caches.open(currentYearMonthString);
}

// If we end up here, return a cache for the latest year/month in the API
// Return a cache for the latest year/month in the API (whether the current month or a previous one)
return await caches.open(latestYearMonthString);
}

static async _isApiFinishedSyncing(yearMonthString) {
return (
(await ApiHelper._getNumberOfLanguagesFromApi(yearMonthString)) ===
(await ApiHelper._getTotalNumberOfLanguages())
);
}

static async _getNumberOfLanguagesFromApi(yearMonthString) {
const where = {
date: yearMonthString,
};
const apiUrl = encodeURI(
`${API_BASE_URL}/api/scores/count?where=${JSON.stringify(
where
)}&access_token=${API_TOKEN}`
);
const response = await fetch(apiUrl);

return (await response.json()).count;
}

static async _getTotalNumberOfLanguages() {
const response = await fetch(
'https://raw.githubusercontent.com/bmaupin/langtrends-api/master/server/boot/classes/languages.json'
);
const languages = await response.json();

return Object.keys(languages).reduce(
(numberOfIncludedLanguages, languageName) => {
if (languages[languageName].include === true) {
numberOfIncludedLanguages += 1;
}
return numberOfIncludedLanguages;
},
0
);
}

static _getCurrentYearMonthString() {
return new Date().toISOString().slice(0, 7);
}
Expand Down

0 comments on commit 999f2b9

Please sign in to comment.