-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtransport-utils.ts
56 lines (51 loc) · 1.58 KB
/
transport-utils.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
const transportIdKey = "[transport-id]";
/**
* Common options for a transport.
*/
export type RPCTransportOptions = {
/**
* An optional unique ID to use for the transport. Useful in cases where
* messages are sent to or received from multiple sources, which causes
* issues.
*/
transportId?: string | number;
/**
* A filter function that determines if a message should be processed or
* ignored. Like the `transportId` option, but more flexible to allow for
* more complex use-cases.
*/
filter?: () => boolean | undefined;
};
/**
* Wraps a message in a transport object, if a transport ID is provided.
*/
export function rpcTransportMessageOut(
data: any,
options: Pick<RPCTransportOptions, "transportId">,
) {
const { transportId } = options;
if (transportId != null) return { [transportIdKey]: transportId, data };
return data;
}
/**
* Determines if a message should be ignored, and if not, returns the message
* too. If the message was wrapped in a transport object, it is unwrapped.
*/
export function rpcTransportMessageIn(
message: any,
options: RPCTransportOptions,
): [ignore: false, message: any] | [ignore: true] {
const { transportId, filter } = options;
const filterResult = filter?.();
if (transportId != null && filterResult != null)
throw new Error(
"Cannot use both `transportId` and `filter` at the same time",
);
let data = message;
if (transportId) {
if (message[transportIdKey] !== transportId) return [true];
data = message.data;
}
if (filterResult === false) return [true];
return [false, data];
}