This repository has been archived by the owner on Aug 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
apollo-fetch.ts
236 lines (210 loc) · 6.04 KB
/
apollo-fetch.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
import {
FetchResult,
RequestAndOptions,
ResponseAndOptions,
RequestsAndOptions,
AfterwareInterface,
MiddlewareInterface,
BatchAfterwareInterface,
BatchMiddlewareInterface,
FetchOptions,
ApolloFetch,
ParsedResponse,
GraphQLRequest,
FetchError,
BatchError,
} from './types';
import 'cross-fetch/polyfill';
type WareStack =
| MiddlewareInterface[]
| BatchMiddlewareInterface[]
| AfterwareInterface[]
| BatchAfterwareInterface[];
function buildWareStack<M>(funcs: WareStack, modifiedObject: M, resolve) {
const next = () => {
if (funcs.length > 0) {
const f = funcs.shift();
if (f) {
f.apply(this, [modifiedObject, next]);
}
} else {
resolve(modifiedObject);
}
};
next();
}
export function constructDefaultOptions(
requestOrRequests: GraphQLRequest | GraphQLRequest[],
options: RequestInit,
): RequestInit {
let body;
try {
body = JSON.stringify(requestOrRequests);
} catch (e) {
throw new Error(
`Network request failed. Payload is not serializable: ${e.message}`,
);
}
return {
body,
method: 'POST',
...options,
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
...options.headers || [],
},
};
}
function throwHttpError(response, error) {
let httpError;
if (response && response.status >= 300) {
httpError = new Error(
`Network request failed with status ${response.status} - "${response.statusText}"`,
);
} else {
httpError = new Error(`Network request failed to return valid JSON`);
}
(httpError as any).response = response;
(httpError as any).parseError = error;
throw httpError as FetchError;
}
function throwBatchError(response) {
let httpError = new Error(`A batched Operation of responses for `);
(httpError as any).response = response;
throw httpError as BatchError;
}
export function createApolloFetch(params: FetchOptions = {}): ApolloFetch {
const { constructOptions, customFetch } = params;
const _uri = params.uri || '/graphql';
const middlewares = [];
const batchedMiddlewares = [];
const afterwares = [];
const batchedAfterwares = [];
const applyMiddlewares = (
requestAndOptions: RequestAndOptions | RequestsAndOptions,
batched: boolean,
): Promise<RequestAndOptions | RequestsAndOptions> => {
return new Promise((resolve, reject) => {
if (batched) {
buildWareStack([...batchedMiddlewares], requestAndOptions, resolve);
} else {
buildWareStack([...middlewares], requestAndOptions, resolve);
}
});
};
const applyAfterwares = (
responseObject: ResponseAndOptions,
batched: boolean,
): Promise<ResponseAndOptions> => {
return new Promise((resolve, reject) => {
if (batched) {
buildWareStack([...batchedAfterwares], responseObject, resolve);
} else {
buildWareStack([...afterwares], responseObject, resolve);
}
});
};
const apolloFetch = function(
request: GraphQLRequest | GraphQLRequest[],
): Promise<FetchResult | FetchResult[]> {
let options = {};
let parseError;
const batched = Array.isArray(request);
const requestObject = <RequestAndOptions | RequestsAndOptions>(batched
? {
requests: request,
options,
}
: {
request,
options,
});
return applyMiddlewares(requestObject, batched)
.then(reqOpts => {
const construct = constructOptions || constructDefaultOptions;
const requestOrRequests =
(<RequestAndOptions>reqOpts).request ||
(<RequestsAndOptions>reqOpts).requests;
return construct(requestOrRequests, reqOpts.options);
})
.then(opts => {
options = { ...opts };
return (customFetch || fetch)(_uri, options);
})
.then(
response =>
response.text().then(raw => {
try {
const parsed = JSON.parse(raw);
(response as ParsedResponse).raw = raw;
(response as ParsedResponse).parsed = parsed;
return <ParsedResponse>response;
} catch (e) {
parseError = e;
//pass parsed raw response onto afterware
(response as ParsedResponse).raw = raw;
return <ParsedResponse>response;
}
}),
//.catch() this should never happen: https://developer.mozilla.org/en-US/docs/Web/API/Body/text
)
.then(response =>
applyAfterwares(
{
response,
options,
},
batched,
),
)
.then(({ response }) => {
if (response.parsed) {
if (batched) {
if (Array.isArray(response.parsed)) {
return response.parsed as FetchResult[];
} else {
throwBatchError(response);
}
} else {
return { ...response.parsed };
}
} else {
throwHttpError(response, parseError);
}
});
};
(apolloFetch as any).use = (middleware: MiddlewareInterface) => {
if (typeof middleware === 'function') {
middlewares.push(middleware);
} else {
throw new Error('Middleware must be a function');
}
return apolloFetch;
};
(apolloFetch as any).useAfter = (afterware: AfterwareInterface) => {
if (typeof afterware === 'function') {
afterwares.push(afterware);
} else {
throw new Error('Afterware must be a function');
}
return apolloFetch;
};
(apolloFetch as any).batchUse = (middleware: BatchMiddlewareInterface) => {
if (typeof middleware === 'function') {
batchedMiddlewares.push(middleware);
} else {
throw new Error('Middleware must be a function');
}
return apolloFetch;
};
(apolloFetch as any).batchUseAfter = (afterware: BatchAfterwareInterface) => {
if (typeof afterware === 'function') {
batchedAfterwares.push(afterware);
} else {
throw new Error('Afterware must be a function');
}
return apolloFetch;
};
return apolloFetch as ApolloFetch;
}