Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): Fix Incremental Delivery payloads deep merging and root patches #3124

Merged
merged 11 commits into from
Apr 1, 2023
6 changes: 6 additions & 0 deletions .changeset/hungry-coins-lie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@urql/core': patch
---

Fix incremental delivery payloads not merging data correctly, or not handling patches on root
results.
120 changes: 120 additions & 0 deletions packages/core/src/internal/fetchSource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,4 +459,124 @@ describe('on text/event-stream', () => {
},
});
});

it('merges deferred results on the root-type', async () => {
fetch.mockResolvedValue({
status: 200,
headers: {
get() {
return 'text/event-stream';
},
},
body: {
getReader: function () {
let cancelled = false;
const results = [
{
done: false,
value: Buffer.from(
wrap({
hasNext: true,
data: {
author: {
id: '1',
__typename: 'Author',
},
},
})
),
},
{
done: false,
value: Buffer.from(
wrap({
incremental: [
{
path: [],
data: { author: { name: 'Steve' } },
},
],
hasNext: true,
})
),
},
{
done: false,
value: Buffer.from(wrap({ hasNext: false })),
},
{ done: true },
];
let count = 0;
return {
cancel: function () {
cancelled = true;
},
read: function () {
if (cancelled) throw new Error('No');

return Promise.resolve(results[count++]);
},
};
},
},
});

const AuthorFragment = gql`
fragment authorFields on Query {
author {
name
}
}
`;

const streamedQueryOperation: Operation = makeOperation(
'query',
{
query: gql`
query {
author {
id
...authorFields @defer
kitten marked this conversation as resolved.
Show resolved Hide resolved
}
}

${AuthorFragment}
`,
variables: {},
key: 1,
},
context
);

const chunks: OperationResult[] = await pipe(
makeFetchSource(streamedQueryOperation, 'https://test.com/graphql', {}),
scan((prev: OperationResult[], item) => [...prev, item], []),
toPromise
);

expect(chunks.length).toEqual(3);

expect(chunks[0].data).toEqual({
author: {
id: '1',
__typename: 'Author',
},
});

expect(chunks[1].data).toEqual({
author: {
id: '1',
name: 'Steve',
__typename: 'Author',
},
});

expect(chunks[2].data).toEqual({
author: {
id: '1',
name: 'Steve',
__typename: 'Author',
},
});
});
});
68 changes: 68 additions & 0 deletions packages/core/src/utils/result.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,43 @@ describe('mergeResultPatch', () => {
});
});

it('should apply incremental stream patches deeply', () => {
const prevResult: OperationResult = {
operation: queryOperation,
data: {
__typename: 'Query',
test: [
{
__typename: 'Test',
},
],
},
stale: false,
hasNext: true,
};

const patch = { name: 'Test' };

const merged = mergeResultPatch(prevResult, {
incremental: [
{
items: [patch],
path: ['test', 0],
},
],
});

expect(merged.data).toStrictEqual({
__typename: 'Query',
test: [
{
__typename: 'Test',
name: 'Test',
},
],
});
});

it('should handle null incremental stream patches', () => {
const prevResult: OperationResult = {
operation: queryOperation,
Expand Down Expand Up @@ -191,6 +228,37 @@ describe('mergeResultPatch', () => {
});
});

it('should handle root incremental stream patches', () => {
const prevResult: OperationResult = {
operation: queryOperation,
data: {
__typename: 'Query',
item: {
test: true,
},
},
stale: false,
hasNext: true,
};

const merged = mergeResultPatch(prevResult, {
incremental: [
{
data: { item: { test2: false } },
path: [],
},
],
});

expect(merged.data).toStrictEqual({
__typename: 'Query',
item: {
test: true,
test2: false,
},
});
});

it('should merge extensions from each patch', () => {
const prevResult: OperationResult = {
operation: queryOperation,
Expand Down
41 changes: 28 additions & 13 deletions packages/core/src/utils/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,22 @@ export const makeResult = (
};
};

const deepMerge = (target: any, source: any) => {
if (typeof target === 'object' && target != null) {
if (
!target.constructor ||
target.constructor === Object ||
Array.isArray(target)
) {
target = Array.isArray(target) ? [...target] : { ...target };
for (const key of Object.keys(source))
target[key] = deepMerge(target[key], source[key]);
return target;
}
}
return source;
};

/** Merges an incrementally delivered `ExecutionResult` into a previous `OperationResult`.
*
* @param prevResult - The {@link OperationResult} that preceded this result.
Expand All @@ -71,7 +87,6 @@ export const mergeResultPatch = (
nextResult: ExecutionResult,
response?: any
): OperationResult => {
let data: ExecutionResult['data'];
let errors = prevResult.error ? prevResult.error.graphQLErrors : [];
let hasExtensions = !!prevResult.extensions || !!nextResult.extensions;
const extensions = { ...prevResult.extensions, ...nextResult.extensions };
Expand All @@ -83,8 +98,8 @@ export const mergeResultPatch = (
incremental = [nextResult as IncrementalPayload];
}

const withData = { data: prevResult.data };
if (incremental) {
data = { ...prevResult.data };
for (const patch of incremental) {
if (Array.isArray(patch.errors)) {
errors.push(...(patch.errors as any));
Expand All @@ -95,33 +110,33 @@ export const mergeResultPatch = (
hasExtensions = true;
}

let prop: string | number = patch.path[0];
let part: Record<string, any> | Array<any> = data as object;
for (let i = 1, l = patch.path.length; i < l; prop = patch.path[i++]) {
let prop: string | number = 'data';
let part: Record<string, any> | Array<any> = withData;
for (let i = 0, l = patch.path.length; i < l; prop = patch.path[i++]) {
part = part[prop] = Array.isArray(part[prop])
? [...part[prop]]
: { ...part[prop] };
}

if (Array.isArray(patch.items)) {
if (patch.items) {
const startIndex = +prop >= 0 ? (prop as number) : 0;
for (let i = 0, l = patch.items.length; i < l; i++)
part[startIndex + i] = patch.items[i];
part[startIndex + i] = deepMerge(
part[startIndex + i],
patch.items[i]
);
} else if (patch.data !== undefined) {
part[prop] =
part[prop] && patch.data
? { ...part[prop], ...patch.data }
: patch.data;
part[prop] = deepMerge(part[prop], patch.data);
}
}
} else {
data = nextResult.data || prevResult.data;
withData.data = nextResult.data || prevResult.data;
errors = (nextResult.errors as any[]) || errors;
}

return {
operation: prevResult.operation,
data,
data: withData.data,
error: errors.length
? new CombinedError({ graphQLErrors: errors, response })
: undefined,
Expand Down
18 changes: 0 additions & 18 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.