-
Notifications
You must be signed in to change notification settings - Fork 9
/
fetcher.js
118 lines (95 loc) · 2.54 KB
/
fetcher.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"use strict"
/* Magic Mirror
* Fetcher
*
* By Michael Teeuw http://michaelteeuw.nl edited for Wunderlist by Marcin Bielecki and Dave Richer
* MIT Licensed.
*/
var WunderlistSDK = require('wunderlist');
/* Fetcher
* Responsible for requesting an update on the set interval and broadcasting the data.
*
* attribute listID string - ID of the Wunderlist list.
* attribute reloadInterval number - Reload interval in milliseconds.
*/
var Fetcher = function (listID, listFrom, reloadInterval, accessToken, clientID) {
var self = this;
if (reloadInterval < 1000) {
reloadInterval = 1000;
}
var reloadTimer = null;
var items = [];
var fetchFailedCallback = function () { };
var itemsReceivedCallback = function () { };
/* private methods */
/* fetchTodos()
* Request the new items.
*/
var fetchTodos = function () {
clearTimeout(reloadTimer);
reloadTimer = null;
var WunderlistAPI = new WunderlistSDK({
accessToken: accessToken,
clientID: clientID
});
WunderlistAPI.initialized.done(function () {
WunderlistAPI.http.tasks.forList(listID)
.done(function (tasks) {
items = tasks.map(task => Object.assign(task, {listFrom}));
self.broadcastItems();
scheduleTimer();
})
.fail(function (resp, code) {
console.error('there was a Wunderlist problem', resp, code);
});
});
};
/* scheduleTimer()
* Schedule the timer for the next update.
*/
var scheduleTimer = function () {
clearTimeout(reloadTimer);
reloadTimer = setTimeout(function () {
fetchTodos();
}, reloadInterval);
};
/* public methods */
/* setReloadInterval()
* Update the reload interval, but only if we need to increase the speed.
*
* attribute interval number - Interval for the update in milliseconds.
*/
this.setReloadInterval = function (interval) {
if (interval > 1000 && interval < reloadInterval) {
reloadInterval = interval;
}
};
/* startFetch()
* Initiate fetchTodos();
*/
this.startFetch = function () {
fetchTodos();
};
/* broadcastItems()
* Broadcast the exsisting items.
*/
this.broadcastItems = function () {
if (items.length <= 0) {
return;
}
itemsReceivedCallback(self);
};
this.onReceive = function (callback) {
itemsReceivedCallback = callback;
};
this.onError = function (callback) {
fetchFailedCallback = callback;
};
this.id = function () {
return listID;
};
this.items = function () {
return items;
};
};
module.exports = Fetcher;