async function fetchData()

in src/wordpress.js [104:145]


async function fetchData(type, endPoint) {
  if (process.env.BUILD_WORDPRESS_THEME === '1') {
    // eslint-disable-next-line no-console
    console.debug(
      "Not fetching any data because BUILD_WORDPRESS_THEME is set to '1'"
    );
    return {};
  }

  if (!endPoint.startsWith('/')) {
    throw new Error(`endPoint="${endPoint}" must start with a slash`);
  }

  const url = `${WORDPRESS_BASE_URL}${endPoint}`;
  // eslint-disable-next-line no-console
  console.debug(`URL for ${type}: ${url}`);

  const noCache = process.env.NO_CACHE === '1';
  if (noCache) {
    // eslint-disable-next-line no-console
    console.debug('Cache is disabled');
  }

  const cache = flatcache.load(type, path.resolve(__dirname, '../cache'));
  const date = new Date();
  // Key set to today's date so at most we should only be fetching everything
  // once per day.
  const key = `${date.getUTCFullYear()}-${
    date.getUTCMonth() + 1
  }-${date.getUTCDate()}`;
  const cachedData = cache.getKey(key);

  if (noCache || !cachedData) {
    const numPages = await getNumPages(url);
    const allData = await fetchAll({ numPages, endPoint: url, type });
    cache.setKey(key, allData);
    cache.save();
    return allData;
  }

  return cachedData;
}