This repository has been archived by the owner on Apr 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 343
/
Copy pathindex.ts
276 lines (238 loc) · 6.95 KB
/
index.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
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
import { Operation } from 'apollo-link';
import { print } from 'graphql/language/printer';
import { InvariantError } from 'ts-invariant';
/*
* Http Utilities: shared across links that make http requests
*/
// XXX replace with actual typings when available
declare var AbortController: any;
//Used for any Error for data from the server
//on a request with a Status >= 300
//response contains no data or errors
export type ServerError = Error & {
response: Response;
result: Record<string, any>;
statusCode: number;
};
//Thrown when server's resonse is cannot be parsed
export type ServerParseError = Error & {
response: Response;
statusCode: number;
bodyText: string;
};
export type ClientParseError = InvariantError & {
parseError: Error;
};
export interface HttpQueryOptions {
includeQuery?: boolean;
includeExtensions?: boolean;
}
export interface HttpConfig {
http?: HttpQueryOptions;
options?: any;
headers?: any; //overrides headers in options
credentials?: any;
}
export interface UriFunction {
(operation: Operation): string;
}
// The body of a GraphQL-over-HTTP-POST request.
export interface Body {
query?: string;
operationName?: string;
variables?: Record<string, any>;
extensions?: Record<string, any>;
}
export interface HttpOptions {
/**
* The URI to use when fetching operations.
*
* Defaults to '/graphql'.
*/
uri?: string | UriFunction;
/**
* Passes the extensions field to your graphql server.
*
* Defaults to false.
*/
includeExtensions?: boolean;
/**
* A `fetch`-compatible API to use when making requests.
*/
fetch?: GlobalFetch['fetch'];
/**
* An object representing values to be sent as headers on the request.
*/
headers?: any;
/**
* The credentials policy you want to use for the fetch call.
*/
credentials?: string;
/**
* Any overrides of the fetch options argument to pass to the fetch call.
*/
fetchOptions?: any;
}
const defaultHttpOptions: HttpQueryOptions = {
includeQuery: true,
includeExtensions: false,
};
const defaultHeaders = {
// headers are case insensitive (https://stackoverflow.com/a/5259004)
accept: '*/*',
'content-type': 'application/json',
};
const defaultOptions = {
method: 'POST',
};
export const fallbackHttpConfig = {
http: defaultHttpOptions,
headers: defaultHeaders,
options: defaultOptions,
};
export const throwServerError = (response, result, message) => {
const error = new Error(message) as ServerError;
error.name = 'ServerError';
error.response = response;
error.statusCode = response.status;
error.result = result;
throw error;
};
//TODO: when conditional types come in ts 2.8, operations should be a generic type that extends Operation | Array<Operation>
export const parseAndCheckHttpResponse = operations => (response: Response) => {
return (
response
.text()
.then(bodyText => {
try {
return JSON.parse(bodyText);
} catch (err) {
const parseError = err as ServerParseError;
parseError.name = 'ServerParseError';
parseError.response = response;
parseError.statusCode = response.status;
parseError.bodyText = bodyText;
return Promise.reject(parseError);
}
})
//TODO: when conditional types come out then result should be T extends Array ? Array<FetchResult> : FetchResult
.then((result: any) => {
if (response.status >= 300) {
//Network error
throwServerError(
response,
result,
`Response not successful: Received status code ${response.status}`,
);
}
//TODO should really error per response in a Batch based on properties
// - could be done in a validation link
if (
!Array.isArray(result) &&
!result.hasOwnProperty('data') &&
!result.hasOwnProperty('errors')
) {
//Data error
throwServerError(
response,
result,
`Server response was missing for query '${
Array.isArray(operations)
? operations.map(op => op.operationName)
: operations.operationName
}'.`,
);
}
return result;
})
);
};
export const checkFetcher = (fetcher: GlobalFetch['fetch']) => {
if (!fetcher && typeof fetch === 'undefined') {
let library: string = 'unfetch';
if (typeof window === 'undefined') library = 'node-fetch';
throw new InvariantError(`
fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/${library}.
For example:
import fetch from '${library}';
import { createHttpLink } from 'apollo-link-http';
const link = createHttpLink({ uri: '/graphql', fetch: fetch });`);
}
};
export const createSignalIfSupported = () => {
if (typeof AbortController === 'undefined')
return { controller: false, signal: false };
const controller = new AbortController();
const signal = controller.signal;
return { controller, signal };
};
export const selectHttpOptionsAndBody = (
operation: Operation,
fallbackConfig: HttpConfig,
...configs: Array<HttpConfig>
) => {
let options: HttpConfig & Record<string, any> = {
...fallbackConfig.options,
headers: fallbackConfig.headers,
credentials: fallbackConfig.credentials,
};
let http: HttpQueryOptions = fallbackConfig.http;
/*
* use the rest of the configs to populate the options
* configs later in the list will overwrite earlier fields
*/
configs.forEach(config => {
options = {
...options,
...config.options,
headers: {
...options.headers,
...config.headers,
},
};
if (config.credentials) options.credentials = config.credentials;
http = {
...http,
...config.http,
};
});
//The body depends on the http options
const { operationName, extensions, variables, query } = operation;
const body: Body = { operationName, variables };
if (http.includeExtensions) (body as any).extensions = extensions;
// not sending the query (i.e persisted queries)
if (http.includeQuery) (body as any).query = print(query);
return {
options,
body,
};
};
export const serializeFetchParameter = (p, label) => {
let serialized;
try {
serialized = JSON.stringify(p);
} catch (e) {
const parseError = new InvariantError(
`Network request failed. ${label} is not serializable: ${e.message}`,
) as ClientParseError;
parseError.parseError = e;
throw parseError;
}
return serialized;
};
//selects "/graphql" by default
export const selectURI = (
operation,
fallbackURI?: string | ((operation: Operation) => string),
) => {
const context = operation.getContext();
const contextURI = context.uri;
if (contextURI) {
return contextURI;
} else if (typeof fallbackURI === 'function') {
return fallbackURI(operation);
} else {
return (fallbackURI as string) || '/graphql';
}
};