-
Notifications
You must be signed in to change notification settings - Fork 907
/
graphql.ts
63 lines (55 loc) · 1.55 KB
/
graphql.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
import { ExecutionResult, GraphQLError } from "graphql";
/** Asserts that an unknown object is a {@link ExecutionResult} */
export function assertExecutionResult(
response: any
): asserts response is ExecutionResult {
if (!response) {
throw new Error(`Expected ExecutionResult but got ${response}`);
}
const type = typeof response;
if (type !== "object") {
throw new Error(`Expected ExecutionResult but got ${type}`);
}
const { data, errors } = response;
if (!data && !errors) {
throw new Error(
`Expected ExecutionResult to have either "data" or "errors" set but none found`
);
}
if (errors) {
if (!Array.isArray(errors)) {
throw new Error(
`Expected errors to be an array but got ${typeof errors}`
);
}
for (const error of errors) {
assertGraphQLError(error);
}
}
}
export function isExecutionResult(response: any): response is ExecutionResult {
try {
assertExecutionResult(response);
return true;
} catch {
return false;
}
}
/** Asserts that an unknown object is a {@link GraphQLError} */
export function assertGraphQLError(
error: unknown
): asserts error is GraphQLError {
if (!error) {
throw new Error(`Expected GraphQLError but got ${error}`);
}
const type = typeof error;
if (type !== "object") {
throw new Error(`Expected GraphQLError but got ${type}`);
}
const { message } = error as GraphQLError;
if (typeof message !== "string") {
throw new Error(
`Expected GraphQLError to have "message" set but got ${typeof message}`
);
}
}