diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-12-06 18:20:54 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-12-07 19:12:11 +0100 |
| commit | b8eb008dd5927fb736e56699637f5f8549965eae (patch) | |
| tree | 648274babea3d3d09ed3e0f5f1fef013f94158fb /src/services/github/fetch-github-repo-meta.ts | |
| parent | 802285872a2c57e7a5e130f32a2b45497d7687f1 (diff) | |
refactor(hooks): replace useGithubApi with useGithubRepoMeta
* use GraphQL API instead of REST (the inconvenient however is that we
now need an authorization token...)
* move fetcher in services
* add tests
* mock response using MSW
Diffstat (limited to 'src/services/github/fetch-github-repo-meta.ts')
| -rw-r--r-- | src/services/github/fetch-github-repo-meta.ts | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/services/github/fetch-github-repo-meta.ts b/src/services/github/fetch-github-repo-meta.ts new file mode 100644 index 0000000..14c8516 --- /dev/null +++ b/src/services/github/fetch-github-repo-meta.ts @@ -0,0 +1,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; +}; |
