API Integration
Overview
The API Integration feature allows the application to interact with external APIs, specifically the GitHub API, to enhance functionality. This integration facilitates operations such as retrieving repository information, handling errors, and managing authentication.
User-facing behavior
- Users can access GitHub repository data directly through the application.
- The application provides informative error messages in case of issues with API requests, such as authorization failures or rate limits.
- Users are prompted to re-authenticate if their GitHub authorization is invalid or missing.
Architecture and data flow
- The integration is built around a modular architecture where API interactions are encapsulated within dedicated functions.
- The flow begins with a user action that triggers an API call to GitHub.
- The application constructs the appropriate request headers, sends the request, and processes the response.
- If the response indicates an error, the application handles it gracefully by logging the issue and notifying the user.
Key implementation details
- The GitHub API base URL is defined as a constant, allowing for easy updates if necessary:
const GITHUB_API_BASE = 'https://api.github.com';
- The
toRepositorySummaryfunction transforms the raw GitHub API response into a more usable format for the application:
const toRepositorySummary = (repo: GitHubRepositoryPayload): GitHubRepositorySummary => ({
owner: repo.owner.login,
name: repo.name,
fullName: repo.full_name,
description: repo.description,
isPrivate: repo.private,
defaultBranch: repo.default_branch,
language: repo.language,
pushedAt: repo.pushed_at,
});
- Error handling is robust, with specific checks for authentication and rate limit issues:
if (response.status === 401) {
throw new AppError(
'GitHub authorization is missing or invalid. Please sign in again.',
'UNAUTHENTICATED',
401,
);
}
- The
getHeadersfunction constructs the necessary headers for GitHub API requests, including authorization tokens:
const getHeaders = (accessToken: string): HeadersInit => ({
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${accessToken}`,
'User-Agent': 'WikiSmith/1.0',
'X-GitHub-Api-Version': '2022-11-28',
});
Key files
apps/web/src/lib/repos/github-api.ts- Central file for handling GitHub API interactions, including request construction and error management. Seeapps/web/src/lib/repos/github-api.ts.apps/web/src/lib/shared/AppError.ts- Defines theAppErrorclass used for error handling throughout the application, ensuring consistent error reporting. Seeapps/web/src/lib/shared/AppError.ts.