aboutsummaryrefslogtreecommitdiffstats
path: root/src/services/github/fetch-github-repo-meta.ts
blob: 14c8516232f3a0b361812d63a3d128b3cf14c129 (plain)
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
import type { GithubRepositoryMeta, Nullable } from '../../types';
import { GITHUB_API } from '../../utils/constants';
import { fetchGraphQL } from '../../utils/helpers';

export type GithubRepositoryResponse = {
  repository: Nullable<GithubRepositoryMeta>;
};

const githubRepoQuery = `query GithubRepository($name: String!, $owner: String!) {
  repository(name: $name, owner: $owner) {
    createdAt
    stargazerCount
    updatedAt
  }
}`;

export type FetchGithubRepoMetaInput = {
  name: string;
  owner: string;
};

export const fetchGithubRepoMeta = async ({
  name,
  owner,
}: FetchGithubRepoMetaInput) => {
  const token = process.env.NEXT_PUBLIC_GITHUB_TOKEN;

  if (!token) throw new Error('Github token is not defined.');

  const response = await fetchGraphQL<GithubRepositoryResponse>({
    headers: {
      Authorization: `Bearer ${token}`,
    },
    query: githubRepoQuery,
    url: GITHUB_API,
    variables: { name, owner },
  });

  if (!response.repository)
    return Promise.reject(
      new Error(`No data found for the following repository ${owner}/${name}.`)
    );

  return response.repository;
};