trphoenix
2018-10-30 f2dafcc61407aef960ee17b576794b1260e84a08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import './SearchResult.dart';
 
class GithubApi {
  final String baseUrl;
  final Map<String, SearchResult> cache;
  final HttpClient client;
 
  GithubApi({
    HttpClient client,
    Map<String, SearchResult> cache,
    this.baseUrl = "https://api.github.com/search/repositories?q=",
  })  : this.client = client ?? new HttpClient(),
        this.cache = cache ?? <String, SearchResult>{};
 
  /// Search Github for repositories using the given term
  Future<SearchResult> search(String term) async {
    if (term.isEmpty) {
      return new SearchResult.noTerm();
    } else if (cache.containsKey(term)) {
      return cache[term];
    } else {
      final result = await _fetchResults(term);
 
      cache[term] = result;
 
      return result;
    }
  }
 
  Future<SearchResult> _fetchResults(String term) async {
    final request = await new HttpClient().getUrl(Uri.parse("$baseUrl$term"));
    final response = await request.close();
    final results = json.decode(await response.transform(utf8.decoder).join());
 
    return new SearchResult.fromJson(results['items']);
  }
}
 
enum SearchResultKind { noTerm, empty, populated }
 
class SearchResultItem {
  final String fullName;
  final String url;
  final String avatarUrl;
 
  toJson() {
    return {'fullName': fullName, 'url': url, 'avatarUrl': avatarUrl};
  }
 
  SearchResultItem(this.fullName, this.url, this.avatarUrl);
 
  factory SearchResultItem.fromJson(Map<String, Object> json) {
    return new SearchResultItem(
      json['full_name'] as String,
      json["html_url"] as String,
      (json["owner"] as Map<String, Object>)["avatar_url"] as String,
    );
  }
}