fetchPinnedRepositories method

Future<List<Repository>> fetchPinnedRepositories(
  1. String username
)

Fetches pinned repositories for a GitHub username using GraphQL API

Implementation

Future<List<Repository>> fetchPinnedRepositories(String username) async {
  final url = Uri.parse('https://api.github.com/graphql');

  // GraphQL query to get pinned repositories
  final query = '''
  {
    user(login: "$username") {
      pinnedItems(first: 6, types: REPOSITORY) {
        edges {
          node {
            ... on Repository {
              name
              description
              url
              stargazers {
                totalCount
              }
              primaryLanguage {
                name
              }
              owner {
                avatarUrl
              }
            }
          }
        }
      }
    }
  }
  ''';

  // Prepare headers - add token if available
  final headers = {
    'Content-Type': 'application/json',
  };

  if (accessToken != null) {
    headers['Authorization'] = 'Bearer $accessToken';
  }

  final response = await client.post(
    url,
    headers: headers,
    body: json.encode({'query': query}),
  );

  if (response.statusCode == 200) {
    final responseData = json.decode(response.body);

    // Check for errors in the GraphQL response
    if (responseData['errors'] != null) {
      throw Exception(responseData['errors'][0]['message']);
    }

    final edges =
        responseData['data']['user']['pinnedItems']['edges'] as List;
    return edges.map((edge) => Repository.fromGraphQLJson(edge)).toList();
  } else {
    throw Exception(
        'GitHub API request failed with status: ${response.statusCode}');
  }
}