All files / src/hooks useCertifications.ts

100% Statements 31/31
100% Branches 5/5
100% Functions 5/5
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 705x   5x 5x 5x                           5x 2x 2x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x   2x                       1x     5x 4x   4x 4x 2x 2x 2x 1x   1x         4x    
import React from 'react';
 
import { endpoints } from '@/constants';
import { getApiClient, GoogleSheetsApiResponse } from '@/lib';
import { handleError } from '@/utils/errors';
 
export type CertificationData = {
  id: number;
  date: string;
  'title_ja-JP': string;
  'title_en-US': string;
  'subject_ja-JP': string;
  'subject_en-US': string;
  favicon: string;
  url: string;
  visible: boolean;
};
 
const fetchData = async () => {
  const client = getApiClient();
  const [certificationsResponse] = await Promise.all([
    client.get<GoogleSheetsApiResponse>(endpoints.getCertifications),
  ]);
 
  const certification = certificationsResponse.data.values[0];
  const certification_id = certification.indexOf('id');
  const certification_date = certification.indexOf('date');
  const certification_titleJaJp = certification.indexOf('title_ja-JP');
  const certification_titleEnUs = certification.indexOf('title_en-US');
  const certification_subjectJaJp = certification.indexOf('subject_ja-JP');
  const certification_subjectEnUs = certification.indexOf('subject_en-US');
  const certification_favicon = certification.indexOf('favicon');
  const certification_url = certification.indexOf('url');
  const certification_visible = certification.indexOf('visible');
 
  const buffer = certificationsResponse.data.values.slice(1, certificationsResponse.data.values.length).map(
    (row) =>
      ({
        id: Number(row[certification_id]),
        date: row[certification_date],
        'title_ja-JP': row[certification_titleJaJp],
        'title_en-US': row[certification_titleEnUs],
        'subject_ja-JP': row[certification_subjectJaJp],
        'subject_en-US': row[certification_subjectEnUs],
        favicon: row[certification_favicon],
        url: row[certification_url],
        visible: row[certification_visible]?.toLowerCase() === 'true' ? true : false,
      } as CertificationData)
  );
  return buffer;
};
 
export const useCertifications = (ready: boolean) => {
  const [cache, setCache] = React.useState<CertificationData[]>();
 
  React.useEffect(() => {
    if (ready && !cache)
      (async () => {
        try {
          const data = await fetchData();
          setCache(data);
        } catch (e) {
          handleError(e);
        }
      })();
  }, [ready, cache]);
 
  return cache;
};