-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathgraphql17Alpha9.ts
More file actions
308 lines (261 loc) · 9.23 KB
/
Copy pathgraphql17Alpha9.ts
File metadata and controls
308 lines (261 loc) · 9.23 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import type {
DocumentNode,
FormattedExecutionResult,
GraphQLFormattedError,
} from "graphql";
import type { ApolloLink } from "@apollo/client/link";
import type { DeepPartial, HKT } from "@apollo/client/utilities";
import { DeepMerger } from "@apollo/client/utilities/internal";
import {
hasDirectives,
isNonEmptyArray,
} from "@apollo/client/utilities/internal";
import { invariant } from "@apollo/client/utilities/invariant";
import type { Incremental } from "../types.js";
export declare namespace GraphQL17Alpha9Handler {
interface GraphQL17Alpha9Result extends HKT {
arg1: unknown; // TData
arg2: unknown; // TExtensions
return: GraphQL17Alpha9Handler.Chunk<Record<string, unknown>>;
}
export interface TypeOverrides {
AdditionalApolloLinkResultTypes: GraphQL17Alpha9Result;
}
export type InitialResult<TData = Record<string, unknown>> = {
data: TData;
errors?: ReadonlyArray<GraphQLFormattedError>;
pending: ReadonlyArray<PendingResult>;
hasNext: boolean;
extensions?: Record<string, unknown>;
};
export type SubsequentResult<TData = unknown> = {
hasNext: boolean;
pending?: ReadonlyArray<PendingResult>;
incremental?: ReadonlyArray<IncrementalResult<TData>>;
completed?: ReadonlyArray<CompletedResult>;
extensions?: Record<string, unknown>;
};
export interface PendingResult {
id: string;
path: Incremental.Path;
label?: string;
}
export interface CompletedResult {
id: string;
errors?: ReadonlyArray<GraphQLFormattedError>;
}
export interface IncrementalDeferResult<TData = Record<string, unknown>> {
errors?: ReadonlyArray<GraphQLFormattedError>;
data: TData;
id: string;
subPath?: Incremental.Path;
extensions?: Record<string, unknown>;
}
export interface IncrementalStreamResult<TData = ReadonlyArray<unknown>> {
errors?: ReadonlyArray<GraphQLFormattedError>;
items: TData;
id: string;
subPath?: Incremental.Path;
extensions?: Record<string, unknown>;
}
export type IncrementalResult<TData = unknown> =
| IncrementalDeferResult<TData>
| IncrementalStreamResult<TData>;
export type Chunk<TData> = InitialResult<TData> | SubsequentResult<TData>;
}
class IncrementalRequest<TData>
implements
Incremental.IncrementalRequest<GraphQL17Alpha9Handler.Chunk<TData>, TData>
{
hasNext = true;
private data: any = {};
private errors: GraphQLFormattedError[] = [];
private extensions: Record<string, any> = {};
private pending: GraphQL17Alpha9Handler.PendingResult[] = [];
// `streamPositions` maps `pending.id` to the index that should be set by the
// next `incremental` stream chunk to ensure the streamed array item is placed
// at the correct point in the data array. `this.data` contains cached
// references with the full array so we can't rely on the array length in
// `this.data` to determine where to place item. This also ensures that items
// updated by the cache between a streamed chunk aren't overwritten by merges
// of future stream items from already merged stream items.
private streamPositions: Record<string, number> = {};
handle(
cacheData: TData | DeepPartial<TData> | null | undefined = this.data,
chunk: GraphQL17Alpha9Handler.Chunk<TData>
): FormattedExecutionResult<TData> {
this.hasNext = chunk.hasNext;
this.data = cacheData;
if (chunk.pending) {
this.pending.push(...chunk.pending);
if ("data" in chunk) {
for (const pending of chunk.pending) {
const dataAtPath = pending.path.reduce(
(data, key) => (data as any)[key],
chunk.data
);
if (Array.isArray(dataAtPath)) {
this.streamPositions[pending.id] = dataAtPath.length;
}
}
}
}
this.merge(chunk, "truncate");
if (hasIncrementalChunks(chunk)) {
for (const incremental of chunk.incremental) {
const pending = this.pending.find(({ id }) => incremental.id === id);
invariant(
pending,
"Could not find pending chunk for incremental value. Please file an issue for the Apollo Client team to investigate."
);
const path = pending.path.concat(incremental.subPath ?? []);
let data: any;
let arrayMerge: DeepMerger.ArrayMergeStrategy = "truncate";
if ("items" in incremental) {
const items = incremental.items as any[];
const parent: any[] = [];
// This creates a sparse array with values set at the indices streamed
// from the server. DeepMerger uses Object.keys and will correctly
// place the values in this array in the correct place
for (let i = 0; i < items.length; i++) {
parent[i + this.streamPositions[pending.id]] = items[i];
}
this.streamPositions[pending.id] += items.length;
data = parent;
} else {
data = incremental.data;
// Check if any pending streams added arrays from deferred data so
// that we can update streamPositions with the initial length of the
// array to ensure future streamed items are inserted at the right
// starting index.
for (const pendingItem of this.pending) {
if (!(pendingItem.id in this.streamPositions)) {
// Check if this incremental data contains array data for the pending path
// The pending path is absolute, but incremental data is relative to the defer
// E.g., pending.path = ["nestedObject"], pendingItem.path = ["nestedObject", "nestedFriendList"]
// incremental.data = { scalarField: "...", nestedFriendList: [...] }
// So we need the path from pending.path onwards
const relativePath = pendingItem.path.slice(pending.path.length);
const dataAtPath = relativePath.reduce(
(data, key) => (data as any)?.[key],
incremental.data
);
if (Array.isArray(dataAtPath)) {
this.streamPositions[pendingItem.id] = dataAtPath.length;
}
}
}
}
for (let i = path.length - 1; i >= 0; i--) {
const key = path[i];
const parent: Record<string | number, any> =
typeof key === "number" ? [] : {};
parent[key] = data;
if (typeof key === "number") {
arrayMerge = "combine";
}
data = parent;
}
this.merge(
{
data,
extensions: incremental.extensions,
errors: incremental.errors,
},
arrayMerge
);
}
}
if ("completed" in chunk && chunk.completed) {
for (const completed of chunk.completed) {
this.pending = this.pending.filter(({ id }) => id !== completed.id);
if (completed.errors) {
this.errors.push(...completed.errors);
}
}
}
const result: FormattedExecutionResult<TData> = { data: this.data };
if (isNonEmptyArray(this.errors)) {
result.errors = this.errors;
}
if (Object.keys(this.extensions).length > 0) {
result.extensions = this.extensions;
}
return result;
}
private merge(
normalized: FormattedExecutionResult<TData>,
arrayMerge: DeepMerger.ArrayMergeStrategy
) {
if (normalized.data !== undefined) {
this.data = new DeepMerger(undefined, { arrayMerge }).merge(
this.data,
normalized.data
);
}
if (normalized.errors) {
this.errors.push(...normalized.errors);
}
Object.assign(this.extensions, normalized.extensions);
}
}
/**
* Provides handling for the incremental delivery specification implemented by
* graphql.js version `17.0.0-alpha.9`.
*/
export class GraphQL17Alpha9Handler
implements Incremental.Handler<GraphQL17Alpha9Handler.Chunk<any>>
{
/** @internal */
isIncrementalResult(
result: ApolloLink.Result<any>
): result is
| GraphQL17Alpha9Handler.InitialResult
| GraphQL17Alpha9Handler.SubsequentResult {
return "hasNext" in result;
}
/** @internal */
prepareRequest(request: ApolloLink.Request): ApolloLink.Request {
if (hasDirectives(["defer", "stream"], request.query)) {
const context = request.context ?? {};
const http = (context.http ??= {});
// https://specs.apollo.dev/incremental/v0.2/
http.accept = [
"multipart/mixed;incrementalSpec=v0.2",
...(http.accept || []),
];
request.context = context;
}
return request;
}
/** @internal */
extractErrors(result: ApolloLink.Result<any>) {
const acc: GraphQLFormattedError[] = [];
const push = ({
errors,
}: {
errors?: ReadonlyArray<GraphQLFormattedError>;
}) => {
if (errors) {
acc.push(...errors);
}
};
if (this.isIncrementalResult(result)) {
push(new IncrementalRequest().handle(undefined, result));
} else {
push(result);
}
if (acc.length) {
return acc;
}
}
/** @internal */
startRequest<TData>(_: { query: DocumentNode }) {
return new IncrementalRequest<TData>();
}
}
function hasIncrementalChunks(
result: Record<string, any>
): result is Required<GraphQL17Alpha9Handler.SubsequentResult> {
return isNonEmptyArray(result.incremental);
}