|
7 | 7 | 'use strict';
|
8 | 8 |
|
9 | 9 | angular.module('githubRepo', [])
|
10 |
| - .factory('GitHubRepo', function ($http, $q) { |
| 10 | + .factory('GitHubRepo', function ($http, $q, $injector) { |
11 | 11 |
|
12 |
| - var githubApi = 'https://api.github.com/repos/'; |
| 12 | + var githubApi = 'https://api.github.com/repos/' |
| 13 | + , $cookieStore = $injector.has('$cookieStore') ? $injector.get('$cookieStore') : null; |
13 | 14 |
|
14 | 15 | /**
|
15 | 16 | * GitHub Repository conntructor.
|
16 | 17 | */
|
17 |
| - function GitHubRepo(repo) { |
18 |
| - this.name = repo.name; |
19 |
| - this.description = repo.description; |
20 |
| - this.url = repo.url; |
21 |
| - this.forks = repo.forks_count; |
22 |
| - this.issues = repo.open_issues; |
23 |
| - this.pushedAt = new Date(repo.pushed_at); |
24 |
| - this.stargazers = repo.stargazers_count; |
25 |
| - this.author = repo.owner.login; |
26 |
| - |
27 |
| - this.fullData = repo; |
| 18 | + function GitHubRepo(data, repo) { |
| 19 | + this.name = data.name; |
| 20 | + this.description = data.description; |
| 21 | + this.url = data.url; |
| 22 | + this.forks = data.forks_count; |
| 23 | + this.issues = data.open_issues; |
| 24 | + this.pushedAt = new Date(data.pushed_at); |
| 25 | + this.stargazers = data.stargazers_count; |
| 26 | + this.author = data.owner.login; |
| 27 | + |
| 28 | + // Save only necessary data to cookie cache. |
| 29 | + this.setCache(repo); |
| 30 | + |
| 31 | + this.fullData = data; |
28 | 32 | }
|
29 | 33 |
|
| 34 | + /** |
| 35 | + * Set cache, if available. |
| 36 | + */ |
| 37 | + GitHubRepo.prototype.setCache = function (repo) { |
| 38 | + $cookieStore && $cookieStore.put('githubRepo:' + repo, this); |
| 39 | + }; |
| 40 | + |
30 | 41 | var factory = {};
|
31 | 42 |
|
| 43 | + /** |
| 44 | + * Get cached data, if any. |
| 45 | + */ |
| 46 | + factory.fecthCached = function (repo) { |
| 47 | + return $cookieStore && $cookieStore.get('githubRepo:' + repo) || null; |
| 48 | + }; |
| 49 | + |
32 | 50 | /**
|
33 | 51 | * Get GitHub Repository object for a given repo.
|
34 | 52 | */
|
35 | 53 | factory.fecth = function (repo) {
|
36 |
| - var deferred = $q.defer(); |
| 54 | + var deferred = $q.defer(), |
| 55 | + cached = factory.fecthCached(repo); |
| 56 | + |
| 57 | + if (cached) { |
| 58 | + deferred.resolve(cached); |
| 59 | + } else { |
| 60 | + $http.get(githubApi + repo, { cache: true }) |
| 61 | + .success(function (data) { |
| 62 | + deferred.resolve(new GitHubRepo(data, repo)); |
| 63 | + }) |
| 64 | + .error(deferred.reject); |
| 65 | + } |
37 | 66 |
|
38 |
| - $http.get(githubApi + repo) |
39 |
| - .success(function (data) { |
40 |
| - deferred.resolve(new GitHubRepo(data)); |
41 |
| - }) |
42 |
| - .error(deferred.reject); |
43 | 67 |
|
44 | 68 | return deferred.promise;
|
45 | 69 | };
|
|
0 commit comments