setAccessToken method

Future<void> setAccessToken()

Implementation

Future<void> setAccessToken() async {
  // if access token hasn't expired, dont make http call
  DateTime now = DateTime.now();
  if (access_expires_at != null) {
    if (now.isBefore(access_expires_at!)) {
      return;
    }
  }

  // todo: handle exceptions
  HttpClient client = HttpClient();
  HttpClientRequest req = await client.getUrl(getAuthUrl());
  req.headers.add("Accept", "application/json");
  req.headers.add("Authorization", "Basic " + b64keySecret);
  HttpClientResponse res = await req.close();

  // u should use `await res.drain()` if u aren't reading the body
  await utf8.decoder.bind(res).forEach((bodyString) {
    dynamic jsondecodeBody = jsonDecode(bodyString);
    access_token = jsondecodeBody["access_token"].toString();
    access_expires_at =
        now.add(Duration(seconds: int.parse(jsondecodeBody["expires_in"].toString())));
  });
}