-
Notifications
You must be signed in to change notification settings - Fork 0
/
petition-pager.ts
263 lines (234 loc) · 9.63 KB
/
petition-pager.ts
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/// <reference path="../node.d.ts" />
import latch = require('../private/latch');
import petitionUtil = require('../private/petition-util');
import util = require('util');
import https = require("https");
import events = require('events');
import loaderExecutor = require('../private/loader-executor');
import equal = require('deep-equal');
import loading = require('./loading');
import petitionLoader = require('./petition-loader');
import petitionPageLoader = require('./petition-page-loader');
import enrichedPetition = require('./enriched-petition');
/// <reference path="./loading.ts" />
/// <reference path="./petition-loader.ts" />
/// <reference path="./petition-page-loader.ts" />
/// <reference path="./enriched-petition.ts" />
export module UkPetitions {
/**
* Configuration for PetitionPager.
*/
export class PetitionPagerConfig {
/**
* The interval.
*/
loadInterval = 500;
/**
* If debug logging should be enabled.
*/
debug = function(message: string, ...objects: any[]) {};
/**
* If detailed petition information should be loaded.
*/
loadDetail = false;
/**
* A function to transform the petitions before stored or emitted.
*/
transformer = function (raw) {
return petitionUtil.recursiveFreeze(new enrichedPetition.UkPetitions.EnrichedPetition(raw));
};
constructor(config: any) {
if (config) {
if (config.loadInterval) {
this.loadInterval = config.loadInterval;
}
if (config.debug) {
this.debug = function() {
console.log.apply(null, arguments);
};
}
if (config.loadDetail !== undefined) {
this.loadDetail = config.loadDetail;
}
if (config.transformer) {
this.transformer = function (data) {
return petitionUtil.recursiveFreeze(config.transformer(data));
};
}
}
}
}
/**
* Loads all the petition data according to a filter.
*/
export class PetitionPager extends events.EventEmitter {
private conf: PetitionPagerConfig;
private agent: https.Agent = new https.Agent({ keepAlive: true, maxSockets: 1 });
private petitionLoader: petitionLoader.UkPetitions.PetitionLoader = new petitionLoader.UkPetitions.PetitionLoader();
private pageLoader: petitionPageLoader.UkPetitions.PetitionPageLoader = new petitionPageLoader.UkPetitions.PetitionPageLoader();
private executor: loaderExecutor.LoaderExecutor;
/**
* Constructor for petition pager.
* @param {PetitionPagerConfig} config - Configuration for PetitionsMonitor.
*/
constructor(config: any) {
super();
this.conf = new PetitionPagerConfig(config);
this.executor = new loaderExecutor.LoaderExecutor(this.conf.loadInterval);
}
private setPetitionData(data) {
var oldData = this.petitions[data.id];
var transformedData = this.conf.transformer(data);
if (!transformedData) {
this.emit('error', new Error('Failed to transform the petition data'));
return;
}
if (oldData) {
// Replace with changed data
if (!equal(oldData, transformedData)) {
this.petitions[data.id] = transformedData;
this.emit('petition', transformedData, oldData);
}
} else {
// Add new data
this.petitions[data.id] = transformedData;
this.petitions.length = this.petitions.length + 1;
this.emit('petition', transformedData);
}
}
private removePetitionData(data) {
var oldData = this.petitions[data.id];
var transformedData = this.conf.transformer(data);
if (!transformedData) {
this.emit('error', new Error('Failed to transform the petition data'));
return;
}
if (oldData) {
delete this.petitions[data.id];
this.emit('removed-petition', transformedData, oldData);
}
}
private detailLoader(id, action, latch, onSuccess) {
// Schedule task for loading petition detail
this.executor.execute(function() {
this.petitionLoader
.load(id)
.onError(function (error) {
this.conf.debug('Error loading petition detail for \'%s\'', action);
this.emit('error', error);
latch.release();
})
.onLoaded(function (data) {
onSuccess(data);
latch.release();
});
});
};
/**
* The petitions map. Maps from petition ID to petition object. Also has
* length property.
*/
petitions: {[key:number]: any; length: number} = {
length: 0
};
/**
* Change the interval between loading pages.
* @param {number} The new interval
* @return Self
*/
setPageLoadInterval(newInterval) {
this.conf.loadInterval = newInterval;
this.executor.setInterval(newInterval);
return this;
};
internalLoadPage(page, emitter, accepter?, remover?) {
var self: PetitionPager = this;
var summaryHandlerProvider = function(latch) {
return function(summary) {
if (remover && remover(summary, self.petitions)) {
if (!self.conf.loadDetail) {
self.conf.debug('Petition \'%s\' removed', summary.attributes.action);
self.removePetitionData(summary);
latch.release();
}
else {
self.detailLoader(summary.id, summary.attributes.action, latch, function(data) {
self.conf.debug('Petition \'%s\' detail removed', summary.attributes.action);
self.removePetitionData(data);
});
}
return;
}
if (accepter && !accepter(summary, self.petitions)) {
// Skip
self.conf.debug('Petition \'%s\' filtered', summary.attributes.action);
latch.release();
return;
}
if (!self.conf.loadDetail) {
// Store summary data
self.conf.debug('Petition \'%s\' summary stored', summary.attributes.action);
self.setPetitionData(summary);
latch.release();
return;
}
self.detailLoader(summary.id, summary.attributes.action, latch, function(data) {
self.conf.debug('Petition \'%s\' detail stored', summary.attributes.action);
self.setPetitionData(data);
});
};
};
var onPageLoaded = function(summary) {
var currentLatch = new latch.Latch(summary.data.length);
currentLatch.onRelease(function () {
self.conf.debug('Page \'%s\' loaded', page);
emitter.emit('page-loaded', summary);
});
summary.data.forEach(summaryHandlerProvider(currentLatch));
};
self.executor.execute(function() {
self.conf.debug('Loading page \'%s\'', page);
self.pageLoader
.load(page)
.onLoaded(onPageLoaded)
.onError(self.emit.bind(self, 'error'));
});
};
/**
* Load petitions without specifying a state.
* @return Self
*/
populateHot() {
var emitter = new events.EventEmitter();
emitter.on('page-loaded', function() {
this.emit('loaded', this);
});
this.internalLoadPage(1, emitter);
return this;
};
/**
* Load all petitions.
* @param accepter A predicate to test if a petition should be accepted.
* @param remover A predicate to test if a petition should be removed.
* @return Self
*/
populate(accepter, remover) {
var emitter = new events.EventEmitter();
var self = this;
// Load the next page
var loadNextPage = function (data) {
if (data.links.next !== null) {
var index = data.links.next.lastIndexOf('/'),
nextPath = data.links.next.substring(index);
self.internalLoadPage(nextPath, emitter, accepter, remover);
}
else {
self.emit('loaded', self);
}
};
emitter.on('page-loaded', loadNextPage);
self.internalLoadPage('/petitions.json?page=1&state=all', emitter, accepter, remover);
return self;
};
}
}