-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathparseAndCheckHttpResponse.ts
57 lines (53 loc) · 1.45 KB
/
parseAndCheckHttpResponse.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
import { Operation } from '../core';
import { throwServerError } from '../utils';
const { hasOwnProperty } = Object.prototype;
export type ServerParseError = Error & {
response: Response;
statusCode: number;
bodyText: string;
};
export function parseAndCheckHttpResponse(
operations: Operation | Operation[],
) {
return (response: Response) => 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;
throw parseError;
}
})
.then((result: any) => {
if (response.status >= 300) {
// Network error
throwServerError(
response,
result,
`Response not successful: Received status code ${response.status}`,
);
}
if (
!Array.isArray(result) &&
!hasOwnProperty.call(result, 'data') &&
!hasOwnProperty.call(result, 'errors')
) {
// Data error
throwServerError(
response,
result,
`Server response was missing for query '${
Array.isArray(operations)
? operations.map(op => op.operationName)
: operations.operationName
}'.`,
);
}
return result;
});
}