forked from michaelgu95/JobQueue
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (60 loc) · 1.55 KB
/
index.js
File metadata and controls
68 lines (60 loc) · 1.55 KB
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
var kue = require('kue'),
queue = kue.createQueue();
var express = require('express'),
app = express();
var redis = require('redis'),
client = redis.createClient();
var request = require('request');
var port = process.env.PORT || 3000;
app.listen(port, function(err) {
if(err) throw err;
console.log('Express server running on localhost:%d', port);
});
app.get('/', function(req, res){
//if user GETs with an id
if(req.param('id')){
var id = req.param('id');
console.log('User requests data with id: ' + id);
//get html stored in redis for the id
client.hget("jobs", id, function(err, value){
if(err){
res.send(err);
}else if(value == null){
res.send('No value stored for id: ' + id + '\n');
console.log('User requests invalid id');
}else{
res.send(value);
console.log("Job complete with value:" + value);
}
})
//otherwise, create new job
}else if(req.param('url')){
newJob(res, req.param('url'));
}
})
function newJob(res, url){
var job = queue.create('new_job', {
url: url
});
job.on('complete', function(){
console.log('Job', job.id, 'has finished');
//send id as result
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(job.id));
})
.on('failed', function(){
console.log('Job', job.id, 'has failed');
});
job.save();
}
queue.process('new_job', function (job, done){
var url = job.data.url.replace( /['"]/g, "" );
request(url, function(error, response, body){
if(!error){
client.hset("jobs", job.id, body);
done();
}else{
console.log(error);
}
})
})