Skip to content

Commit

Permalink
feat(utils/mergeDeep): concat arrays if respectArrays true
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Nov 22, 2023
1 parent e1fb8bb commit 22301d1
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
4 changes: 2 additions & 2 deletions packages/merge/src/extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ExtensionsObject, Maybe, mergeDeep, SchemaExtensions } from '@graphql-t
export { extractExtensionsFromSchema } from '@graphql-tools/utils';

export function mergeExtensions(extensions: SchemaExtensions[]): SchemaExtensions {
return mergeDeep(extensions);
return mergeDeep(extensions, false, true);
}

function applyExtensionObject(
Expand All @@ -15,7 +15,7 @@ function applyExtensionObject(
return;
}

obj.extensions = mergeDeep([obj.extensions || {}, extensions || {}]);
obj.extensions = mergeDeep([obj.extensions || {}, extensions || {}], false, true);
}

export function applyExtensions(
Expand Down
13 changes: 9 additions & 4 deletions packages/utils/src/mergeDeep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type UnboxIntersection<T> = T extends { 0: infer U } ? U : never;
export function mergeDeep<S extends any[]>(
sources: S,
respectPrototype = false,
respectArrays = false,
): UnboxIntersection<UnionToIntersection<BoxedTupleTypes<S>>> & any {
const target = sources[0] || {};
const output = {};
Expand All @@ -35,9 +36,13 @@ export function mergeDeep<S extends any[]>(
if (!(key in output)) {
Object.assign(output, { [key]: source[key] });
} else {
output[key] = mergeDeep([output[key], source[key]] as S, respectPrototype);
output[key] = mergeDeep(
[output[key], source[key]] as S,
respectPrototype,
respectArrays,
);
}
} else if (Array.isArray(output[key])) {
} else if (respectArrays && Array.isArray(output[key])) {
if (Array.isArray(source[key])) {
output[key].push(...source[key]);
} else {
Expand All @@ -47,13 +52,13 @@ export function mergeDeep<S extends any[]>(
Object.assign(output, { [key]: source[key] });
}
}
} else if (Array.isArray(target)) {
} else if (respectArrays && Array.isArray(target)) {
if (Array.isArray(source)) {
target.push(...source);
} else {
target.push(source);
}
} else if (Array.isArray(source)) {
} else if (respectArrays && Array.isArray(source)) {
return [target, ...source];
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/tests/mergeDeep.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,6 @@ describe('mergeDeep', () => {
it('merges arrays', () => {
const x = { a: [1, 2] };
const y = { a: [3, 4] };
expect(mergeDeep([x, y])).toEqual({ a: [1, 2, 3, 4] });
expect(mergeDeep([x, y], false, true)).toEqual({ a: [1, 2, 3, 4] });
});
});

0 comments on commit 22301d1

Please sign in to comment.