-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathserver.js
71 lines (56 loc) · 1.86 KB
/
server.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
'use strict';
var crypto = require('crypto');
var connect = require('connect');
var Q = require('q');
var fetchComponents = require('./component-list');
var componentListEntity;
var HTTP_PORT = process.env.PORT || 8011;
var UPDATE_INTERVAL_IN_MINUTES = 60;
function getComponentListEntity() {
var deferred = Q.defer();
fetchComponents().then(function (list) {
console.log('Finished fetching data from GitHub', '' + new Date());
// TODO: Find a way for the promise not to return null so this isn't needed
list = list.filter(function (el) {
return el !== null && el !== undefined;
});
var entity = {json: JSON.stringify(list)};
var shasum = crypto.createHash('sha1');
shasum.update(entity.json);
entity.etag = shasum.digest('hex');
deferred.resolve(entity);
// update the entity
componentListEntity = deferred.promise;
}).fail(function (err) {
deferred.reject(err);
});
return deferred.promise;
}
function getComponentList(request, response, next) {
componentListEntity.then(function (entity) {
// allow CORS
response.setHeader('ETag', entity.etag);
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Content-Type', 'application/json');
if (request.headers['if-none-match'] === entity.etag) {
response.statusCode = 304;
response.end();
return;
}
response.statusCode = 200;
response.end(new Buffer(entity.json));
}).fail(function(err) {
next(err);
});
}
// componentListEntity - promise {etag: '', json: ''}
// using a promise so that clients can connect and wait for the initial entity
componentListEntity = getComponentListEntity();
connect()
.use(connect.errorHandler())
.use(connect.timeout(10000))
.use(connect.logger('dev'))
.use(getComponentList)
.listen(HTTP_PORT);
setInterval(getComponentListEntity, UPDATE_INTERVAL_IN_MINUTES * 1000 * 60);
console.log('Server running on port ' + HTTP_PORT);