-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclustter-api.js
82 lines (63 loc) · 2 KB
/
clustter-api.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
var cluster = require('cluster');
// forking from master
if (cluster.isMaster) {
// counting cpus
var cpuCount = require('os').cpus().length;
// worker for each cpu
for (var i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
} else {
var express = require('express'),
mongoose = require('mongoose'),
DB = mongoose.createConnection('mongodb://localhost/clustter'),
story = require('./models/story.js')(DB);
api = express();
var port = 5000;
// var allowCrossDomain = function (req, res, next) {
// res.header('Access-Control-Allow-Origin', '*');
// res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// // intercept OPTIONS method
// if ('OPTIONS' == req.method) {
// res.send(200);
// }
// else {
// next();
// }
// };
// api.use(allowCrossDomain);
// opening database connection
DB.on('error', console.error.bind(console, 'database error.'));
DB.on('open', init);
var cachedStories = {};
function init () {
getFeed();
};
var getFeed = function () {
var time = getQueryTime();
story
.find({ updated: { $lt: time.lt, $gt: time.gt } })
.lean()
.exec(function (err, stories) {
cachedStories = stories;
});
};
var getQueryTime = function () {
var now = new Date(),
hour = now.getHours();
return (hour > 12) ? {gt: new Date().setHours(12), lt: new Date().setHours(24) } : { gt: new Date().setHours(00), lt: new Date().setHours(12) };
};
var server = api.listen(port, function () {
console.log(cluster.worker.id, 'api running on port', port);
});
api.get('/', function (req, res) {
res.jsonp({ status: 'running' });
});
api.get('/stories', function (req, res) {
res.jsonp({ stories: cachedStories });
});
api.get('/story/:id', function (req, res) {
res.jsonp({ story: cachedStories[req.params.id] });
});
}