-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
584 lines (530 loc) · 16.5 KB
/
client.ts
File metadata and controls
584 lines (530 loc) · 16.5 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
import type {
GraphqlClient,
GraphqlClientConfig,
GraphqlConnectionConfig,
GraphqlOptions,
} from "./types.ts";
import type { GraphqlErrorItem } from "./types.ts";
import type { GraphqlResponse } from "./response.ts";
import {
GraphqlExecutionError,
type GraphqlFailureError,
GraphqlNetworkError,
} from "./errors.ts";
import {
GraphqlResponseErrorImpl,
GraphqlResponseFailureImpl,
GraphqlResponseSuccessImpl,
} from "./response.ts";
import { AbortError, TimeoutError } from "@probitas/client";
import { getLogger } from "@logtape/logtape";
const logger = getLogger(["probitas", "client", "graphql"]);
/**
* Convert fetch error to appropriate failure error.
*/
function convertFetchError(error: unknown): GraphqlFailureError {
if (error instanceof AbortError || error instanceof TimeoutError) {
return error;
}
if (error instanceof Error) {
if (error.name === "AbortError") {
return new AbortError(error.message, { cause: error });
}
return new GraphqlNetworkError(error.message, { cause: error });
}
return new GraphqlNetworkError(String(error));
}
/**
* Merge headers from multiple sources.
* Returns Headers instance to properly support multi-value headers.
*/
function mergeHeaders(
...sources: (HeadersInit | undefined)[]
): Headers {
const result = new Headers();
for (const source of sources) {
if (source) {
const headers = new Headers(source);
for (const [key, value] of headers) {
result.set(key, value);
}
}
}
return result;
}
/**
* Resolve endpoint URL from string or connection config.
*/
function resolveEndpointUrl(url: string | GraphqlConnectionConfig): string {
if (typeof url === "string") {
return url;
}
const protocol = url.protocol ?? "http";
const host = url.host ?? "localhost";
const port = url.port;
const path = url.path ?? "/graphql";
const portSuffix = port ? `:${port}` : "";
return `${protocol}://${host}${portSuffix}${path}`;
}
/**
* GraphQL response structure from server.
*/
interface GraphqlResponseBody<T> {
data?: T | null;
errors?: GraphqlErrorItem[];
extensions?: Record<string, unknown>;
}
/**
* GraphqlClient implementation.
*/
class GraphqlClientImpl implements GraphqlClient {
readonly config: GraphqlClientConfig;
readonly #endpointUrl: string;
constructor(config: GraphqlClientConfig) {
this.config = config;
this.#endpointUrl = resolveEndpointUrl(config.url);
// Log client creation
logger.debug("GraphQL client created", {
endpoint: this.#endpointUrl,
wsEndpoint: config.wsEndpoint,
headersCount: config.headers ? Object.keys(config.headers).length : 0,
});
}
// deno-lint-ignore no-explicit-any
query<TData = any, TVariables = Record<string, any>>(
query: string,
variables?: TVariables,
options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>> {
return this.execute<TData, TVariables>(query, variables, options);
}
// deno-lint-ignore no-explicit-any
mutation<TData = any, TVariables = Record<string, any>>(
mutation: string,
variables?: TVariables,
options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>> {
return this.execute<TData, TVariables>(mutation, variables, options);
}
// deno-lint-ignore no-explicit-any
async execute<TData = any, TVariables = Record<string, any>>(
document: string,
variables?: TVariables,
options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>> {
const headers = mergeHeaders(
{ "Content-Type": "application/json" },
this.config.headers,
options?.headers,
);
const body = JSON.stringify({
query: document,
variables: variables ?? undefined,
operationName: options?.operationName,
});
// Log request start
logger.debug("GraphQL request starting", {
endpoint: this.#endpointUrl,
operationName: options?.operationName,
hasVariables: variables !== undefined,
variableKeys: variables ? Object.keys(variables) : [],
headers: [...headers.keys()],
});
// Trace log with full details
logger.trace("GraphQL request details", {
query: document,
variables,
});
const fetchFn = this.config.fetch ?? globalThis.fetch;
const startTime = performance.now();
// Determine whether to throw on error (request option > config > default false)
const shouldThrow = options?.throwOnError ?? this.config.throwOnError ??
false;
// Attempt fetch - may fail due to network errors
let rawResponse: Response;
try {
rawResponse = await fetchFn(this.#endpointUrl, {
method: "POST",
headers,
body,
signal: options?.signal,
});
} catch (error) {
const duration = performance.now() - startTime;
const failureError = convertFetchError(error);
if (shouldThrow) {
throw failureError;
}
return new GraphqlResponseFailureImpl<TData>({
url: this.#endpointUrl,
error: failureError,
duration,
});
}
const duration = performance.now() - startTime;
// Handle HTTP errors (4xx/5xx) as Failure
if (!rawResponse.ok) {
await rawResponse.body?.cancel();
const networkError = new GraphqlNetworkError(
`HTTP ${rawResponse.status}: ${rawResponse.statusText}`,
);
if (shouldThrow) {
throw networkError;
}
return new GraphqlResponseFailureImpl<TData>({
url: this.#endpointUrl,
error: networkError,
duration,
});
}
// Parse JSON response
let responseBody: GraphqlResponseBody<TData>;
try {
responseBody = await rawResponse.json();
} catch (error) {
const networkError = new GraphqlNetworkError(
"Failed to parse response JSON",
{ cause: error },
);
if (shouldThrow) {
throw networkError;
}
return new GraphqlResponseFailureImpl<TData>({
url: this.#endpointUrl,
error: networkError,
duration,
});
}
// Create appropriate response type
let response: GraphqlResponse<TData>;
if (responseBody.errors && responseBody.errors.length > 0) {
// GraphQL execution error
const executionError = new GraphqlExecutionError(responseBody.errors);
response = new GraphqlResponseErrorImpl<TData>({
url: this.#endpointUrl,
data: responseBody.data ?? null,
error: executionError,
extensions: responseBody.extensions ?? null,
duration,
status: rawResponse.status,
raw: rawResponse,
});
} else {
// Success
response = new GraphqlResponseSuccessImpl<TData>({
url: this.#endpointUrl,
data: responseBody.data ?? null,
extensions: responseBody.extensions ?? null,
duration,
status: rawResponse.status,
raw: rawResponse,
});
}
// Log response
logger.debug("GraphQL response received", {
endpoint: this.#endpointUrl,
operationName: options?.operationName,
status: rawResponse.status,
duration: `${duration.toFixed(2)}ms`,
hasData: responseBody.data !== undefined && responseBody.data !== null,
errorCount: responseBody.errors?.length ?? 0,
contentType: rawResponse.headers.get("content-type"),
});
// Trace log with response data content
logger.trace("GraphQL response data", {
data: responseBody.data,
});
// Throw error if required
if (!response.ok && shouldThrow) {
throw response.error;
}
return response;
}
// deno-lint-ignore no-explicit-any
async *subscribe<TData = any, TVariables = Record<string, any>>(
document: string,
variables?: TVariables,
options?: GraphqlOptions,
): AsyncIterable<GraphqlResponse<TData>> {
const wsEndpoint = this.config.wsEndpoint;
if (!wsEndpoint) {
throw new GraphqlNetworkError(
"WebSocket endpoint (wsEndpoint) is not configured",
);
}
// Log subscription start
logger.debug("GraphQL subscription starting", {
wsEndpoint,
operationName: options?.operationName,
hasVariables: variables !== undefined,
variableKeys: variables ? Object.keys(variables) : [],
});
const ws = new WebSocket(wsEndpoint, "graphql-transport-ws");
// Wait for connection to open
await new Promise<void>((resolve, reject) => {
const openHandler = () => {
logger.debug("GraphQL WebSocket connection opened", {
wsEndpoint,
});
ws.onopen = null;
ws.onerror = null;
resolve();
};
const errorHandler = (event: Event) => {
const errorMessage = (event as ErrorEvent).message ?? "unknown error";
ws.onopen = null;
ws.onerror = null;
reject(
new GraphqlNetworkError(
`WebSocket connection failed: ${errorMessage}`,
),
);
};
ws.onopen = openHandler;
ws.onerror = errorHandler;
});
// Send connection_init message
ws.send(JSON.stringify({ type: "connection_init" }));
// Wait for connection_ack
await new Promise<void>((resolve, reject) => {
let cleaned = false;
const cleanup = () => {
if (!cleaned) {
cleaned = true;
ws.removeEventListener("message", handler);
}
};
const handler = (event: MessageEvent) => {
const message = JSON.parse(event.data);
if (message.type === "connection_ack") {
cleanup();
resolve();
} else if (message.type === "connection_error") {
cleanup();
reject(
new GraphqlNetworkError(
`WebSocket connection error: ${JSON.stringify(message.payload)}`,
),
);
}
};
ws.addEventListener("message", handler);
// Ensure cleanup even if promise is cancelled/rejected externally
// (though this is unlikely in practice)
});
// Generate a unique subscription ID
const subscriptionId = crypto.randomUUID();
// Send start/subscribe message
const subscribeMessage = {
id: subscriptionId,
type: "subscribe",
payload: {
query: document,
variables: variables ?? undefined,
operationName: options?.operationName,
},
};
ws.send(JSON.stringify(subscribeMessage));
logger.debug("GraphQL subscription message sent", {
subscriptionId,
operationName: options?.operationName,
});
// Create an async iterator to yield responses
const responseQueue: GraphqlResponse<TData>[] = [];
let resolveNext: (() => void) | null = null;
let done = false;
let error: Error | null = null;
const messageHandler = (event: MessageEvent) => {
const message = JSON.parse(event.data);
switch (message.type) {
case "next": {
const startTime = performance.now();
const payload = message.payload as GraphqlResponseBody<TData>;
let response: GraphqlResponse<TData>;
if (payload.errors && payload.errors.length > 0) {
const executionError = new GraphqlExecutionError(payload.errors);
response = new GraphqlResponseErrorImpl<TData>({
url: wsEndpoint,
data: payload.data ?? null,
error: executionError,
extensions: payload.extensions ?? null,
duration: performance.now() - startTime,
status: 200,
raw: new Response(JSON.stringify(payload)),
});
} else {
response = new GraphqlResponseSuccessImpl<TData>({
url: wsEndpoint,
data: payload.data ?? null,
extensions: payload.extensions ?? null,
duration: performance.now() - startTime,
status: 200,
raw: new Response(JSON.stringify(payload)),
});
}
logger.debug("GraphQL subscription message received", {
subscriptionId,
operationName: options?.operationName,
hasData: payload.data !== undefined && payload.data !== null,
errorCount: payload.errors?.length ?? 0,
});
responseQueue.push(response);
resolveNext?.();
break;
}
case "error": {
error = new GraphqlNetworkError(
`Subscription error: ${JSON.stringify(message.payload)}`,
);
done = true;
resolveNext?.();
break;
}
case "complete": {
logger.debug("GraphQL subscription completed", {
subscriptionId,
operationName: options?.operationName,
});
done = true;
resolveNext?.();
break;
}
}
};
ws.addEventListener("message", messageHandler);
// Handle WebSocket close
ws.onclose = () => {
logger.debug("GraphQL WebSocket closed", {
subscriptionId,
operationName: options?.operationName,
});
done = true;
resolveNext?.();
};
ws.onerror = () => {
error = new GraphqlNetworkError("WebSocket error during subscription");
done = true;
resolveNext?.();
};
try {
while (true) {
if (responseQueue.length > 0) {
const response = responseQueue.shift()!;
// Determine whether to throw on errors
const shouldThrow = options?.throwOnError ??
this.config.throwOnError ?? false;
if (!response.ok && shouldThrow && response.error) {
throw response.error;
}
yield response;
} else if (done) {
if (error) {
throw error;
}
break;
} else {
await new Promise<void>((resolve) => {
resolveNext = resolve;
});
resolveNext = null;
}
}
} finally {
// Clean up: send stop message and close WebSocket
logger.debug("GraphQL subscription cleanup", {
subscriptionId,
operationName: options?.operationName,
});
ws.removeEventListener("message", messageHandler);
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ id: subscriptionId, type: "complete" }));
// Wait for WebSocket to close to avoid resource leaks
await new Promise<void>((resolve) => {
ws.onclose = () => resolve();
ws.close();
});
}
// Clean up event handlers
ws.onclose = null;
ws.onerror = null;
}
}
close(): Promise<void> {
return Promise.resolve();
}
[Symbol.asyncDispose](): Promise<void> {
return this.close();
}
}
/**
* Create a new GraphQL client instance.
*
* The client provides methods for executing GraphQL queries, mutations,
* and subscriptions with automatic error handling and response parsing.
*
* @param config - Client configuration including URL and default options
* @returns A new GraphQL client instance
*
* @example Basic query
* ```ts
* import { createGraphqlClient } from "@probitas/client-graphql";
*
* const client = createGraphqlClient({
* url: "http://localhost:4000/graphql",
* });
*
* const response = await client.query(`
* query GetUser($id: ID!) {
* user(id: $id) { id name email }
* }
* `, { id: "123" });
*
* console.log(response.data);
* await client.close();
* ```
*
* @example Using connection config object
* ```ts
* import { createGraphqlClient } from "@probitas/client-graphql";
*
* const client = createGraphqlClient({
* url: { host: "api.example.com", port: 443, protocol: "https" },
* });
* await client.close();
* ```
*
* @example Mutation with error handling
* ```ts
* import { createGraphqlClient } from "@probitas/client-graphql";
*
* const client = createGraphqlClient({ url: "http://localhost:4000/graphql" });
*
* const response = await client.mutation(`
* mutation CreateUser($input: CreateUserInput!) {
* createUser(input: $input) { id }
* }
* `, { input: { name: "Alice", email: "alice@example.com" } });
*
* if (response.ok) {
* console.log("Created user:", (response.data as any).createUser.id);
* }
*
* await client.close();
* ```
*
* @example Using `await using` for automatic cleanup
* ```ts
* import { createGraphqlClient } from "@probitas/client-graphql";
*
* await using client = createGraphqlClient({
* url: "http://localhost:4000/graphql",
* });
* const response = await client.query(`{ __typename }`);
* // Client automatically closed when scope exits
* ```
*/
export function createGraphqlClient(
config: GraphqlClientConfig,
): GraphqlClient {
return new GraphqlClientImpl(config);
}