forked from tiagosiebler/kucoin-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket-util.ts
71 lines (62 loc) · 1.88 KB
/
websocket-util.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
import WebSocket from 'isomorphic-ws';
/** Should be one WS key per unique URL */
export const WS_KEY_MAP = {
spotPublicV1: 'spotPublicV1',
spotPrivateV1: 'spotPrivateV1',
futuresPublicV1: 'futuresPublicV1',
futuresPrivateV1: 'futuresPrivateV1',
} as const;
/** This is used to differentiate between each of the available websocket streams */
export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP];
/**
* Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters.
*
* - Topic: the topic this event is for
* - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters.
*/
export interface WsTopicRequest<
TWSTopic extends string = string,
TWSPayload = any,
> {
topic: TWSTopic;
payload?: TWSPayload;
}
/**
* Conveniently allow users to request a topic either as string topics or objects (containing string topic + params)
*/
export type WsTopicRequestOrStringTopic<
TWSTopic extends string,
TWSPayload = any,
> = WsTopicRequest<TWSTopic, TWSPayload> | string;
export interface MessageEventLike {
target: WebSocket;
type: 'message';
data: string;
}
export function isMessageEvent(msg: unknown): msg is MessageEventLike {
if (typeof msg !== 'object' || !msg) {
return false;
}
const message = msg as MessageEventLike;
return message['type'] === 'message' && typeof message['data'] === 'string';
}
/**
* #305: ws.terminate() is undefined in browsers.
* This only works in node.js, not in browsers.
* Does nothing if `ws` is undefined. Does nothing in browsers.
*/
export function safeTerminateWs(
ws?: WebSocket | any,
fallbackToClose?: boolean,
): boolean {
if (!ws) {
return false;
}
if (typeof ws['terminate'] === 'function') {
ws.terminate();
return true;
} else if (fallbackToClose) {
ws.close();
}
return false;
}