-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclients.ts
128 lines (116 loc) · 3.35 KB
/
clients.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
// deno-lint-ignore-file no-explicit-any
import {
CloseCode,
GRAPHQL_TRANSPORT_WS_PROTOCOL,
MessageType,
} from "./constants.ts";
import {
NextMessage,
PartialGraphQLParameters,
SubscribeMessage,
} from "./types.ts";
import { isString } from "./deps.ts";
import { parseMessage } from "./parse.ts";
export interface GraphQLWebSocketEventMap {
next: MessageEvent<NextMessage>;
}
/** GraphQL over WebSocket client specification.
* ```ts
* import { createClient } from "https://deno.land/x/graphql_websocket@$VERSION/mod.ts";
*
* const Client = createClient(`wss://<ENDPOINT>`);
* Client.addEventListener("next", ({ data }) => {
* console.log(data);
* });
*
* Client.subscribe({
* query: `subscription { test }`,
* });
* ```
*/
export interface Client extends WebSocket {
subscribe(params: PartialGraphQLParameters): void;
addEventListener<K extends keyof GraphQLWebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: GraphQLWebSocketEventMap[K]) => any,
options?: boolean | AddEventListenerOptions,
): void;
}
export class ClientImpl extends WebSocket implements Client {
#ws: WebSocket;
#queue: (string | ArrayBufferLike | Blob | ArrayBufferView)[] = [];
constructor(url: string | URL) {
super(url);
this.#ws = new WebSocket(url, GRAPHQL_TRANSPORT_WS_PROTOCOL);
this.#ws.addEventListener("open", () => {
while (this.#queue.length > 0) {
const message = this.#queue.pop();
if (isString(message)) {
this.#ws.send(message);
}
}
}, {
once: true,
});
}
#send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
if (this.#ws.readyState === this.#ws.OPEN) {
this.#ws.send(data);
} else {
this.#queue.push(data);
}
}
subscribe(params: PartialGraphQLParameters): void {
const id = crypto.randomUUID();
const msg: SubscribeMessage = {
id,
type: MessageType.Subscribe,
payload: params,
};
this.#send(JSON.stringify(msg));
}
addEventListener<
K extends keyof (WebSocketEventMap & GraphQLWebSocketEventMap),
>(
type: K,
listener: (
this: WebSocket,
ev: (WebSocketEventMap & GraphQLWebSocketEventMap)[K],
) => any,
options?: boolean | AddEventListenerOptions | undefined,
): void;
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions | undefined,
): void {
if (["next"].includes(type)) {
this.#ws.addEventListener("message", (ev) => {
const [data, error] = parseMessage(ev.data);
if (!data) {
return this.close(CloseCode.BadRequest, error.message);
}
switch (data.type) {
case MessageType.Next: {
// deno-lint-ignore ban-types
(listener as Function)({ ...ev, data });
}
}
}, options);
} else {
this.#ws.addEventListener(type, listener, options);
}
}
}
/** Create GraphQL over WebSocket client.
* @param url The URL to which to connect; this should be the URL to which the WebSocket server will respond.
* @throws SyntaxError
* ```ts
* import { createClient } from "https://deno.land/x/graphql_websocket@$VERSION/mod.ts";
*
* const Client = createClient(`wss://<ENDPOINT>`);
* ```
*/
export function createClient(url: string | URL): Client {
return new ClientImpl(url);
}