-
Notifications
You must be signed in to change notification settings - Fork 93
/
on.js
83 lines (64 loc) · 2.13 KB
/
on.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
/* @flow */
import { ZalgoPromise } from '@krakenjs/zalgo-promise/src';
import { addRequestListener } from '../drivers';
import { WILDCARD } from '../conf';
import type { ServerOptionsType, HandlerType, CancelableType } from '../types';
const getDefaultServerOptions = () : ServerOptionsType => {
// $FlowFixMe
return {};
};
export function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {
if (!name) {
throw new Error('Expected name');
}
options = options || getDefaultServerOptions();
if (typeof options === 'function') {
handler = options;
options = getDefaultServerOptions();
}
if (!handler) {
throw new Error('Expected handler');
}
const winOrProxyWin = options.window;
const domain = options.domain || WILDCARD;
const successHandler = handler || options.handler;
const errorHandler = options.errorHandler || (err => {
throw err;
});
const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {
handler: successHandler,
handleError: errorHandler
});
return {
cancel() {
requestListener.cancel();
}
};
}
type CancelableZalgoPromise<T> = ZalgoPromise<T> & {|
cancel : () => void
|};
export function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {
options = options || getDefaultServerOptions();
if (typeof options === 'function') {
handler = options;
options = getDefaultServerOptions();
}
const promise = new ZalgoPromise();
let listener; // eslint-disable-line prefer-const
options.errorHandler = (err) => {
listener.cancel();
promise.reject(err);
};
listener = on(name, options, event => {
listener.cancel();
promise.resolve(event);
if (handler) {
return handler(event);
}
});
// $FlowFixMe
promise.cancel = listener.cancel;
// $FlowFixMe
return promise;
}