-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathresource-watcher-0.1.0.js
48 lines (43 loc) · 1.07 KB
/
resource-watcher-0.1.0.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
'use strict';
const resourceWatcher = function (url, conf) {
let token = function (conf) {
return conf && (conf = conf.Authorization) &&
(conf = typeof conf === 'string' &&
conf.split('=')) &&
Array.isArray(conf) && conf[1];
};
url += '?token=' + token(conf);
url += conf.timeout ? '&timeout=' + conf.timeout : '';
let es = new EventSource(url); //jshint ignore: line
let close = function () {
es.close();
};
const makeHandler = function (handler, close) {
return function (e) {
if (close) {
close();
}
return handler(e.data ? JSON.parse(e.data) : e);
};
};
const on = function (event, handler) {
switch (event) {
case 'connect':
es.onopen = makeHandler(handler);
break;
case 'change':
es.onmessage = makeHandler(handler);
break;
case 'error':
es.onerror = makeHandler(handler, close);
break;
default:
console.error('Unknown event type:' + event);
break;
}
};
return {
close: close,
on: on,
};
};