Skip to content

Commit

Permalink
(core) - Fix stringifyVariables (and thus operation keys) for Fi… (#650)
Browse files Browse the repository at this point in the history
* Fix stringifyVariables for Files

* Add changeset

* Fix hashing by generating random, stable key for non-objects

Any object without any enumerable keys that isn't a plain
object will now receive a random key.

* Add more details to changeset
  • Loading branch information
kitten authored Mar 22, 2020
1 parent f328f50 commit e3754da
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
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

0 comments on commit e3754da

Please sign in to comment.