Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.

(core) - Fix maskTypename not handling nested arrays (#2074)

* fix arrays in maskTypename

* fix typing issue

* fix issue with nested data

Changed files
+38 -16
.changeset
packages
+5
.changeset/metal-monkeys-knock.md
···
+
---
+
'@urql/core': patch
+
---
+
+
Fix issue where `maskTypename` would ignore array shapes
+14
packages/core/src/utils/maskTypename.test.ts
···
).toEqual({ id: 1, author: { id: 2 } });
});
+
it('works with nested arrays', () => {
+
expect(
+
maskTypename({
+
__typename: 'Todo',
+
id: 1,
+
nodes: [[4, 5]],
+
author: {
+
id: 2,
+
__typename: 'Author',
+
},
+
})
+
).toEqual({ id: 1, nodes: [[4, 5]], author: { id: 2 } });
+
});
+
it('strips typename from nested objects with arrays', () => {
expect(
maskTypename({
+19 -16
packages/core/src/utils/maskTypename.ts
···
export const maskTypename = (data: any): any => {
if (!data || typeof data !== 'object') return data;
-
return Object.keys(data).reduce((acc, key: string) => {
-
const value = data[key];
-
if (key === '__typename') {
-
Object.defineProperty(acc, '__typename', {
-
enumerable: false,
-
value,
-
});
-
} else if (Array.isArray(value)) {
-
acc[key] = value.map(maskTypename);
-
} else if (value && typeof value === 'object' && '__typename' in value) {
-
acc[key] = maskTypename(value);
-
} else {
-
acc[key] = value;
-
}
+
return Object.keys(data).reduce(
+
(acc, key: string) => {
+
const value = data[key];
+
if (key === '__typename') {
+
Object.defineProperty(acc, '__typename', {
+
enumerable: false,
+
value,
+
});
+
} else if (Array.isArray(value)) {
+
acc[key] = value.map(maskTypename);
+
} else if (value && typeof value === 'object' && '__typename' in value) {
+
acc[key] = maskTypename(value);
+
} else {
+
acc[key] = value;
+
}
-
return acc;
-
}, {});
+
return acc;
+
},
+
Array.isArray(data) ? [] : {}
+
);
};