exchange method

Future<ExchangeResponse> exchange(
  1. String code, [
  2. String? origin
])

Exchanges the given code for a token.

Implementation

Future<ExchangeResponse> exchange(String code, [String? origin]) {
  final headers = <String, String>{
    'Accept': 'application/json',
    'content-type': 'application/json',
  };

  if (origin != null) {
    headers['Origin'] = origin;
  }

  final body = GitHubJson.encode(<String, dynamic>{
    'client_id': clientId,
    'client_secret': clientSecret,
    'code': code,
    'redirect_uri': redirectUri,
  });

  return (github == null ? http.Client() : github!.client)
      .post(Uri.parse('$baseUrl/access_token'), body: body, headers: headers)
      .then((response) {
        final json = jsonDecode(response.body) as Map<String, dynamic>;
        if (json['error'] != null) {
          throw Exception(json['error']);
        }
        return ExchangeResponse(
          json['access_token'],
          json['token_type'],
          (json['scope'] as String).split(','),
        );
      });
}