getContents method

Future<List<GitHubContent>> getContents(
  1. String path
)

Fetches contents from the GitHub API at the specified path.

The path should be a valid GitHub API endpoint path (e.g., '/repos/username/repo/contents').

Returns a Future that completes with a list of GitHubContent objects.

Throws a GitHubApiException if:

  • The request fails (non-200 status code)
  • The response format is invalid
  • The response cannot be parsed

Implementation

Future<List<GitHubContent>> getContents(String path) async {
  final token = _token ?? Platform.environment['GITHUB_TOKEN'];
  try {
    final response = await _httpClient.get(
      Uri.parse(path),
      headers: {
        'Accept': 'application/vnd.github+json',
        if (token != null) 'Authorization': 'Bearer $token',
      },
    );

    if (response.statusCode != 200) {
      throw GitHubApiException(
        'Failed to fetch contents from $path. Status code: ${response.statusCode}',
        statusCode: response.statusCode,
      );
    }

    final jsonBody = jsonDecode(response.body) as dynamic;

    if (jsonBody is Map<String, dynamic>) {
      return [GitHubContent.fromJson(jsonBody)];
    }

    if (jsonBody is List) {
      final contents = await _processContentList(
        jsonBody.cast<Map<String, dynamic>>(),
      );
      return contents;
    }

    throw const FormatException(
      'Unexpected response format: Expected Map or List',
    );
  } on FormatException catch (e) {
    throw GitHubApiException('Failed to parse response: ${e.message}');
  } on http.ClientException catch (e) {
    throw GitHubApiException(
      'Network error while fetching contents: ${e.message}',
    );
  }
}