-
Notifications
You must be signed in to change notification settings - Fork 2
/
gitHubCache.js
102 lines (91 loc) · 3.64 KB
/
gitHubCache.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const http = require('http');
const https = require('https');
const url = require('url');
const NodeCache = require("node-cache");
class GitHubCache {
constructor(options) {
this.options = options;
this.cache = new NodeCache({ stdTTL: 360 }); // time to live in seconds -> 60 min
}
getStats(owner, project) {
return new Promise((resolve, reject) => {
const self = this;
this.cache.get('github/' + owner + '/' + project, function (err, value) {
if (!err) {
if (value == undefined) {
console.log('Key github/' + owner + '/' + project + ' not found');
console.log('Start sync for github/' + owner + '/' + project);
self.syncStats(owner, project)
.then((stats) => resolve(stats))
.catch((err) => {
console.error(err);
reject(err);
});
} else {
resolve(value);
}
} else {
console.error(err);
reject(err)
}
});
});
}
syncStats(owner, project) {
return new Promise((resolve, reject) => {
this.getStatsFromGithub(owner, project).then((body) => {
this.cache.set('github/' + owner + '/' + project, body, function (err, success) {
if (!err && success) {
console.log('Sync done for github/' + owner + '/' + project);
resolve(body);
} else {
console.error(err);
reject(err);
}
});
}).catch((err) => {
console.error(err);
reject(err);
});
})
}
getStatsFromGithub(owner, project) {
return new Promise((resolve, reject) => {
let gitHubApiUrl = this.options.url;
console.log('GET %s//%s:%s%s', gitHubApiUrl.protocol, gitHubApiUrl.hostname, gitHubApiUrl.port, '/repos/' + owner + '/' + project);
let headers = {
'user-agent': 'node.js'
}
if (this.options.apiToken) headers['Authorization'] = 'token ' + this.options.apiToken;
let protocol = gitHubApiUrl.protocol == 'https:' ? https : http;
protocol.request({
hostname: gitHubApiUrl.hostname,
port: gitHubApiUrl.port,
path: '/repos/' + owner + '/' + project,
method: 'GET',
headers: headers
}, function (res) {
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
if (res.statusCode == 200) {
console.log('Remaining requests:', res.headers['x-ratelimit-remaining'] + ' of ' + res.headers['x-ratelimit-limit']);
resolve(body)
} else {
console.error(res.statusCode, res.statusMessage);
reject({
statusCode: res.statusCode,
statusMessage: res.statusMessage
});
}
});
}).on('error', function (err) {
console.error(err);
reject(err);
}).end();
})
}
}
module.exports = GitHubCache;