All files / src/utils githubApi.js

100% Statements 14/14
100% Branches 6/6
100% Functions 2/2
100% Lines 14/14

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 525x 5x       5x                         5x 4x                 5x 5x 5x 4x                   2x   3x 1x   2x   3x      
const GITHUB_API_URL = 'https://api.github.com/graphql';
const GITHUB_TOKEN = process.env.REACT_APP_GITHUB_TOKEN;
 
// README is fetched from raw.githubusercontent.com per-repo to avoid GraphQL blob
// parsing edge-cases and token exposure in query payloads.
const PINNED_REPOS_QUERY = `
  query getPinned {
    user(login: "keglev") {
      pinnedItems(first: 6, types: [REPOSITORY]) {
        nodes { __typename ... on Repository { name description url } }
      }
    }
  }
`;
 
// axios publishes ESM and CJS; require() resolves to CJS in Jest to avoid import errors.
// eslint-disable-next-line global-require
function getAxios() {
  const mod = require('axios');
  return mod.default ? mod.default : mod;
}
 
/**
 * Fetches the six pinned GitHub repositories for the portfolio owner via the GraphQL API.
 * Returns an empty array on any network or auth failure so the UI degrades gracefully.
 *
 * @returns {Promise<object[]>} Array of repository nodes from the GitHub GraphQL API
 */
export const fetchPinnedRepositories = async () => {
  try {
    const axios = getAxios();
    const response = await axios.post(
      GITHUB_API_URL,
      { query: PINNED_REPOS_QUERY },
      {
        headers: {
          Authorization: `Bearer ${GITHUB_TOKEN}`,
          'X-GitHub-Api-Version': '2022-11-28',
        },
      }
    );
    return response.data.data.user.pinnedItems.nodes;
  } catch (error) {
    if (error.response && error.response.status === 401) {
      console.error('GitHub token is expired or invalid.');
    } else {
      console.error('Error fetching pinned repositories:', error);
    }
    return [];
  }
};