-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
80 lines (71 loc) · 2.44 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
72
73
74
75
76
77
78
79
80
var port = process.env.PORT || 5000;
var mongoose = require('mongoose');
var request = require('request');
var _ = require('underscore');
var configDB = require('./config/database.js')(mongoose);
var Assignment = require('./models/assignment');
var BASE_URL = 'https://api.dev.workmarket.com/api/v1'; // Point to the environment you are using
var TOKEN = ''; // Replace with your token
var SECRET = ''; // Replace with your secret
var ACCESS_TOKEN = ''; // Don't set this
var lastTimeStamp = Date.now();
var pollingIntervalInMinutes = 2; // PLEASE do not go below 2 (minutes) here!
var updateTokenRunner = setInterval(refreshAccessToken(TOKEN, SECRET), (1000 * 60 * 60 * 24));
var updateRunner = setInterval(pollForUpdates, (pollingIntervalInMinutes * 1000 * 60));
function refreshAccessToken(token, secret, callback) {
request.post({
url: BASE_URL + '/authorization/request',
form: {token: token, secret: secret}
}, function (error, response, body) {
var apiResponse = JSON.parse(body);
if (!error && response.statusCode == 200) {
ACCESS_TOKEN = apiResponse.response.access_token;
if (callback) {
callback();
}
} else {
console.log(error);
}
console.log(apiResponse);
})
}
function processAssignmentList(assignmentList) {
_.each(assignmentList, function (assignment) {
getAssignment(assignment.id, function (assignment) {
Assignment.findOneAndUpdate({'id': assignment.id}, assignment, {upsert: true}, function(err, assignment) {
if (err) {
console.log(err);
return;
}
console.log(JSON.stringify(assignment));
});
})
});
}
function pollForUpdates() {
request.get({
url: BASE_URL + '/assignments/list_updated?access_token=' + ACCESS_TOKEN + '&modified_since=' + lastTimeStamp
}, function (error, response, body) {
var apiResponse = JSON.parse(body);
if (!error && response.statusCode == 200) {
// update timestamp
lastTimeStamp = apiResponse.meta.timestamp;
processAssignmentList(apiResponse.response.data);
} else {
console.log(error);
}
console.log(apiResponse);
})
}
function getAssignment(id, callback) {
request.get({
url: BASE_URL + '/assignments/get?access_token=' + ACCESS_TOKEN + '&id=' + id
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var responseJSON = JSON.parse(body);
callback(responseJSON.response);
} else {
console.log(error);
}
});
}