-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclient.ts
More file actions
160 lines (143 loc) · 4.25 KB
/
client.ts
File metadata and controls
160 lines (143 loc) · 4.25 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
/**
* ORM Client - Runtime GraphQL executor
* @generated by @constructive-io/graphql-codegen
* DO NOT EDIT - changes will be overwritten
*/
import type {
GraphQLAdapter,
GraphQLError,
QueryResult,
} from '@constructive-io/graphql-query/runtime';
import { createFetch } from '@constructive-io/graphql-query/runtime';
export type {
GraphQLAdapter,
GraphQLError,
QueryResult,
} from '@constructive-io/graphql-query/runtime';
/**
* Default adapter that uses fetch for HTTP requests.
*
* When no custom fetch is provided, uses @constructive-io/fetch which
* handles *.localhost DNS rewriting and Host header preservation in
* Node.js. Pass a custom fetch to override for test mocking or custom
* proxy/credentials.
*/
export class FetchAdapter implements GraphQLAdapter {
private headers: Record<string, string>;
private fetchFn: typeof globalThis.fetch;
constructor(
private endpoint: string,
headers?: Record<string, string>,
fetchFn?: typeof globalThis.fetch
) {
this.headers = headers ?? {};
this.fetchFn = fetchFn ?? createFetch();
}
async execute<T>(document: string, variables?: Record<string, unknown>): Promise<QueryResult<T>> {
const response = await this.fetchFn(this.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
...this.headers,
},
body: JSON.stringify({
query: document,
variables: variables ?? {},
}),
});
if (!response.ok) {
return {
ok: false,
data: null,
errors: [{ message: `HTTP ${response.status}: ${response.statusText}` }],
};
}
const json = (await response.json()) as {
data?: T;
errors?: GraphQLError[];
};
if (json.errors && json.errors.length > 0) {
return {
ok: false,
data: null,
errors: json.errors,
};
}
return {
ok: true,
data: json.data as T,
errors: undefined,
};
}
setHeaders(headers: Record<string, string>): void {
this.headers = { ...this.headers, ...headers };
}
getEndpoint(): string {
return this.endpoint;
}
}
/**
* Configuration for creating an ORM client.
* Either provide endpoint (and optional headers/fetch) for HTTP requests,
* or provide a custom adapter for alternative execution strategies.
*/
export interface OrmClientConfig {
/** GraphQL endpoint URL (required if adapter not provided) */
endpoint?: string;
/** Default headers for HTTP requests (only used with endpoint) */
headers?: Record<string, string>;
/**
* Custom fetch implementation. Defaults to createFetch() from
* @constructive-io/graphql-query/runtime which handles *.localhost
* DNS and Host headers in Node.js. Pass your own for test mocking
* or custom proxy/credentials.
*/
fetch?: typeof globalThis.fetch;
/** Custom adapter for GraphQL execution (overrides endpoint/headers/fetch) */
adapter?: GraphQLAdapter;
}
/**
* Error thrown when GraphQL request fails
*/
export class GraphQLRequestError extends Error {
constructor(
public readonly errors: GraphQLError[],
public readonly data: unknown = null
) {
const messages = errors.map((e) => e.message).join('; ');
super(`GraphQL Error: ${messages}`);
this.name = 'GraphQLRequestError';
}
}
export class OrmClient {
private adapter: GraphQLAdapter;
constructor(config: OrmClientConfig) {
if (config.adapter) {
this.adapter = config.adapter;
} else if (config.endpoint) {
this.adapter = new FetchAdapter(config.endpoint, config.headers, config.fetch);
} else {
throw new Error('OrmClientConfig requires either an endpoint or a custom adapter');
}
}
async execute<T>(document: string, variables?: Record<string, unknown>): Promise<QueryResult<T>> {
return this.adapter.execute<T>(document, variables);
}
/**
* Set headers for requests.
* Only works if the adapter supports headers.
*/
setHeaders(headers: Record<string, string>): void {
if (this.adapter.setHeaders) {
this.adapter.setHeaders(headers);
}
}
/**
* Get the endpoint URL.
* Returns empty string if the adapter doesn't have an endpoint.
*/
getEndpoint(): string {
return this.adapter.getEndpoint?.() ?? '';
}
}