Skip to content

Commit 619fcf6

Browse files
author
Lucas Constantino
committed
Added simple caching system to avoid multiple github api requesting.
1 parent 7fffbc0 commit 619fcf6

File tree

1 file changed

+43
-19
lines changed

1 file changed

+43
-19
lines changed

angular-github-repo.js

+43-19
Original file line numberDiff line numberDiff line change
@@ -7,39 +7,63 @@
77
'use strict';
88

99
angular.module('githubRepo', [])
10-
.factory('GitHubRepo', function ($http, $q) {
10+
.factory('GitHubRepo', function ($http, $q, $injector) {
1111

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;
1314

1415
/**
1516
* GitHub Repository conntructor.
1617
*/
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;
2832
}
2933

34+
/**
35+
* Set cache, if available.
36+
*/
37+
GitHubRepo.prototype.setCache = function (repo) {
38+
$cookieStore && $cookieStore.put('githubRepo:' + repo, this);
39+
};
40+
3041
var factory = {};
3142

43+
/**
44+
* Get cached data, if any.
45+
*/
46+
factory.fecthCached = function (repo) {
47+
return $cookieStore && $cookieStore.get('githubRepo:' + repo) || null;
48+
};
49+
3250
/**
3351
* Get GitHub Repository object for a given repo.
3452
*/
3553
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+
}
3766

38-
$http.get(githubApi + repo)
39-
.success(function (data) {
40-
deferred.resolve(new GitHubRepo(data));
41-
})
42-
.error(deferred.reject);
4367

4468
return deferred.promise;
4569
};

0 commit comments

Comments
 (0)