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

(core) - Fix stringifyVariables (and thus operation keys) for Files #650

Merged
merged 4 commits into from
Mar 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wicked-cows-heal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@urql/core': patch
---

Add support for variables that contain non-plain objects without any enumerable keys, e.g. `File` or `Blob`. In this case `stringifyVariables` will now use a stable (but random) key, which means that mutations containing `File`s — or other objects like this — will now be distinct, as they should be.
17 changes: 16 additions & 1 deletion packages/core/src/utils/stringifyVariables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,22 @@ it('throws for circular structures', () => {
}).toThrow();
});

it('stringifies date correctly', () => {
it('stringifies dates correctly', () => {
const date = new Date('2019-12-11T04:20:00');
expect(stringifyVariables(date)).toBe(date.toJSON());
});

it('stringifies dictionaries (Object.create(null)) correctly', () => {
expect(stringifyVariables(Object.create(null))).toBe('{}');
});

it('stringifies files correctly', () => {
const file = new File([0] as any, 'test.js');
Object.defineProperty(file, 'lastModified', { value: 123 });
const str = stringifyVariables(file);
expect(str).toBe(stringifyVariables(file));

const otherFile = new File([0] as any, 'otherFile.js');
Object.defineProperty(otherFile, 'lastModified', { value: 234 });
expect(str).not.toBe(stringifyVariables(otherFile));
});
10 changes: 10 additions & 0 deletions packages/core/src/utils/stringifyVariables.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const seen = new Set();
const cache = new WeakMap();

const stringify = (x: any): string => {
if (x === undefined) {
Expand Down Expand Up @@ -29,6 +30,15 @@ const stringify = (x: any): string => {
}

const keys = Object.keys(x).sort();
if (!keys.length && x.constructor && x.constructor !== Object) {
const key =
cache.get(x) ||
Math.random()
.toString(36)
.slice(2);
cache.set(x, key);
return `{"__key":"${key}"}`;
}

seen.add(x);
out = '{';
Expand Down