{"size": 897, "ext": "js", "max_stars_repo_path": "src/getFetchStrategyAlgorithm.js", "max_stars_repo_name": "mathieuprog/graphql-light", "max_stars_repo_stars_event_min_datetime": "2021-02-15T23:59:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T12:12:17.000Z", "max_issues_repo_path": "src/getFetchStrategyAlgorithm.js", "max_issues_repo_name": "mathieuprog/graphql-light", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/getFetchStrategyAlgorithm.js", "max_forks_repo_name": "mathieuprog/graphql-light", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 6, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.9166666667, "max_line_length": 63, "alphanum_fraction": 0.602006689}
import FetchStrategy from './FetchStrategy';
import NotFoundInCacheError from './NotFoundInCacheError';

export default function getFetchStrategyAlgorithm(strategy) {
  return async ({ isCached, fetchData, cacheData }) => {
    switch (strategy) {
      default:
        throw new Error(`unknown strategy ${strategy}`);

      case FetchStrategy.CACHE_AND_NETWORK:
        if (!isCached) {
          cacheData(await fetchData());
        } else {
          fetchData().then(cacheData);
        }
        break;

      case FetchStrategy.CACHE_FIRST:
        if (!isCached) {
          cacheData(await fetchData());
        }
        break;

      case FetchStrategy.NETWORK_ONLY:
        cacheData(await fetchData());
        break;

      case FetchStrategy.CACHE_ONLY:
        if (!isCached) {
          throw new NotFoundInCacheError('not found in cache');
        }
        break;
    }
  }
}
