Skip to content

Commit

Permalink
cacheResourcesFromConfig: reload the cache when config is downloaded
Browse files Browse the repository at this point in the history
We recently added the ability to refresh the config from inside the app.
But whenever the config is downloaded for the first time, we cache the resources referenced in it by URL. Subsequent config downloads would still use the resources from the first time.

fetchUrlCached now accepts options to pass through to the fetch API; if cache is 'reload', we will skip checking our localStorage cache for a previously stored value. This option will also cause the fetch API will also skip its own internal cache

The result of this is that when we refresh the config, URL-referenced resources inside it will also be refreshed.
  • Loading branch information
JGreenlee committed Apr 17, 2024
1 parent 03673a4 commit d83f4d4
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
4 changes: 2 additions & 2 deletions www/js/config/dynamicConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,11 @@ function cacheResourcesFromConfig(config: AppConfig) {
if (config.survey_info?.surveys) {
Object.values(config.survey_info.surveys).forEach((survey) => {
if (!survey?.['formPath']) throw new Error(i18next.t('config.survey-missing-formpath'));
fetchUrlCached(survey['formPath']);
fetchUrlCached(survey['formPath'], { cache: 'reload' });
});
}
if (config.label_options) {
fetchUrlCached(config.label_options);
fetchUrlCached(config.label_options, { cache: 'reload' });
}
}

Expand Down
9 changes: 5 additions & 4 deletions www/js/services/commHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,18 @@ import { TimestampRange } from '../types/diaryTypes';

/**
* @param url URL endpoint for the request
* @param fetchOpts (optional) options for the fetch request. If 'cache' is set to 'reload', the cache will be ignored
* @returns Promise of the fetched response (as text) or cached text from local storage
*/
export async function fetchUrlCached(url) {
export async function fetchUrlCached(url: string, fetchOpts?: RequestInit) {
const stored = localStorage.getItem(url);
if (stored) {
if (stored && fetchOpts?.cache != 'reload') {
logDebug(`fetchUrlCached: found cached data for url ${url}, returning`);
return Promise.resolve(stored);
}
try {
logDebug(`fetchUrlCached: found no cached data for url ${url}, fetching`);
const response = await fetch(url);
logDebug(`fetchUrlCached: cache had ${stored} for url ${url}, not using; fetching`);
const response = await fetch(url, fetchOpts);
const text = await response.text();
localStorage.setItem(url, text);
logDebug(`fetchUrlCached: fetched data for url ${url}, returning`);
Expand Down

0 comments on commit d83f4d4

Please sign in to comment.