-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathfetchGraphQL.mjs
195 lines (179 loc) · 6.86 KB
/
fetchGraphQL.mjs
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
// @ts-check
/**
* @import { CacheValue } from "./Cache.mjs"
* @import {
* GraphQLResult,
* GraphQLResultError,
* GraphQLResultErrorLoadingFetch,
* GraphQLResultErrorResponseHttpStatus,
* GraphQLResultErrorResponseJsonParse,
* GraphQLResultErrorResponseMalformed,
* } from "./types.mjs"
*/
const ERROR_CODE_FETCH_ERROR = "FETCH_ERROR";
const ERROR_CODE_RESPONSE_HTTP_STATUS = "RESPONSE_HTTP_STATUS";
const ERROR_CODE_RESPONSE_JSON_PARSE_ERROR = "RESPONSE_JSON_PARSE_ERROR";
const ERROR_CODE_RESPONSE_MALFORMED = "RESPONSE_MALFORMED";
/**
* Fetches a GraphQL operation, always resolving a
* {@link GraphQLResult GraphQL result} suitable for use as a
* {@link CacheValue cache value}, even if there are
* {@link FetchGraphQLResultError errors}.
* @param {string} fetchUri Fetch URI for the GraphQL API.
* @param {RequestInit} [fetchOptions] Fetch options.
* @returns {Promise<FetchGraphQLResult>} Resolves a result suitable for use as
* a {@link CacheValue cache value}. Shouldn’t reject.
* @see [MDN `fetch` parameters docs](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters).
* @see [Polyfillable `fetch` options](https://github.github.io/fetch/#options).
* Don’t use other options if `fetch` is polyfilled for Node.js or legacy
* browsers.
*/
export default function fetchGraphQL(fetchUri, fetchOptions) {
/** @type {FetchGraphQLResult} */
const result = {};
/** @type {Array<FetchGraphQLResultError>} */
const resultErrors = [];
const fetcher =
typeof fetch === "function"
? fetch
: () => Promise.reject(new TypeError("Global `fetch` API unavailable."));
return fetcher(fetchUri, fetchOptions)
.then(
// Fetch ok.
(response) => {
// Allow the response to be read in the cache value, but prevent it from
// serializing to JSON when sending SSR cache to the client for
// hydration.
Object.defineProperty(result, "response", { value: response });
if (!response.ok)
resultErrors.push(
/** @type {GraphQLResultErrorResponseHttpStatus} */ ({
message: `HTTP ${response.status} status.`,
extensions: {
client: true,
code: ERROR_CODE_RESPONSE_HTTP_STATUS,
statusCode: response.status,
statusText: response.statusText,
},
}),
);
return response.json().then(
// Response JSON parse ok.
(json) => {
// It’s not safe to assume that the response data format conforms to
// the GraphQL spec.
// https://spec.graphql.org/October2021/#sec-Response-Format
if (typeof json !== "object" || !json || Array.isArray(json))
resultErrors.push(
/** @type {GraphQLResultErrorResponseMalformed}*/ ({
message: "Response JSON isn’t an object.",
extensions: {
client: true,
code: ERROR_CODE_RESPONSE_MALFORMED,
},
}),
);
else {
const hasErrors = "errors" in json;
const hasData = "data" in json;
if (!hasErrors && !hasData)
resultErrors.push(
/** @type {GraphQLResultErrorResponseMalformed}*/ ({
message:
"Response JSON is missing an `errors` or `data` property.",
extensions: {
client: true,
code: ERROR_CODE_RESPONSE_MALFORMED,
},
}),
);
else {
// The `errors` field should be an array, or not set.
// https://spec.graphql.org/October2021/#sec-Errors
if (hasErrors)
if (!Array.isArray(json.errors))
resultErrors.push(
/** @type {GraphQLResultErrorResponseMalformed}*/ ({
message:
"Response JSON `errors` property isn’t an array.",
extensions: {
client: true,
code: ERROR_CODE_RESPONSE_MALFORMED,
},
}),
);
else resultErrors.push(...json.errors);
// The `data` field should be an object, null, or not set.
// https://spec.graphql.org/October2021/#sec-Data
if (hasData)
if (
// Note that `null` is an object.
typeof json.data !== "object" ||
Array.isArray(json.data)
)
resultErrors.push(
/** @type {GraphQLResultErrorResponseMalformed}*/ ({
message:
"Response JSON `data` property isn’t an object or null.",
extensions: {
client: true,
code: ERROR_CODE_RESPONSE_MALFORMED,
},
}),
);
else result.data = json.data;
}
}
},
// Response JSON parse error.
({ message }) => {
resultErrors.push(
/** @type {GraphQLResultErrorResponseJsonParse} */ ({
message: "Response JSON parse error.",
extensions: {
client: true,
code: ERROR_CODE_RESPONSE_JSON_PARSE_ERROR,
jsonParseErrorMessage: message,
},
}),
);
},
);
},
// Fetch error.
({ message }) => {
resultErrors.push(
/** @type {GraphQLResultErrorLoadingFetch} */ ({
message: "Fetch error.",
extensions: {
client: true,
code: ERROR_CODE_FETCH_ERROR,
fetchErrorMessage: message,
},
}),
);
},
)
.then(() => {
if (resultErrors.length) result.errors = resultErrors;
return result;
});
}
/**
* {@linkcode fetchGraphQL} {@link GraphQLResult GraphQL result}.
* @typedef {GraphQLResult<FetchGraphQLResultError>} FetchGraphQLResult
*/
/**
* {@linkcode fetchGraphQL} {@link GraphQLResult.errors GraphQL result error}.
* @typedef {FetchGraphQLResultErrorLoading
* | GraphQLResultError} FetchGraphQLResultError
*/
/**
* {@linkcode fetchGraphQL} {@link GraphQLResult.errors GraphQL result error}
* that’s generated on the client, not the GraphQL server.
* @typedef {GraphQLResultErrorLoadingFetch
* | GraphQLResultErrorResponseHttpStatus
* | GraphQLResultErrorResponseJsonParse
* | GraphQLResultErrorResponseMalformed
* } FetchGraphQLResultErrorLoading
*/