repositories method Null safety

Stream<Repository> repositories(
  1. String query,
  2. {String? sort,
  3. int pages = 2}
)

Search for repositories using query. Since the Search Rate Limit is small, this is a best effort implementation.

API docs: https://developer.github.com/v3/search/#search-repositories

Implementation

Stream<Repository> repositories(String query, {String? sort, int pages = 2}) {
  final params = <String, dynamic>{'q': query};
  if (sort != null) {
    params['sort'] = sort;
  }

  final controller = StreamController<Repository>();

  var isFirst = true;

  PaginationHelper(github)
      .fetchStreamed('GET', '/search/repositories',
          params: params, pages: pages)
      .listen((response) {
    if (response.statusCode == 403 &&
        response.body.contains('rate limit') &&
        isFirst) {
      throw RateLimitHit(github);
    }

    isFirst = false;

    final input = jsonDecode(response.body);

    if (input['items'] == null) {
      return;
    }

    final items = input['items'] as List;

    items.map((item) => Repository.fromJson(item)).forEach(controller.add);
  }).onDone(controller.close);

  return controller.stream;
}