Skip to content

Commit

Permalink
fix(core): Use documentId for operation hash if it's available
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Apr 28, 2024
1 parent a4ea19c commit e6db80e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/forty-walls-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@urql/core': patch
---

Use `documentId` from persisted documents for document keys, when it's available.
10 changes: 10 additions & 0 deletions packages/core/src/utils/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ describe('createRequest', () => {
variables: { test: 5 },
});
});

it('should hash persisted documents consistently', () => {
const doc = parse('{ testG }');
const docPersisted = parse('{ testG }');
(docPersisted as any).documentId = 'testG';

const req = createRequest(doc, undefined);
const reqPersisted = createRequest(docPersisted, undefined);
expect(req.key).not.toBe(reqPersisted.key);
});
});

describe('stringifyDocument ', () => {
Expand Down
19 changes: 14 additions & 5 deletions packages/core/src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import type {
RequestExtensions,
} from '../types';

type PersistedDocumentNode = TypedDocumentNode & {
documentId?: string;
};

/** A `DocumentNode` annotated with its hashed key.
* @internal
*/
Expand Down Expand Up @@ -90,11 +94,16 @@ export const stringifyDocument = (
const hashDocument = (
node: string | DefinitionNode | DocumentNode
): HashValue => {
let key = phash(stringifyDocument(node));
// Add the operation name to the produced hash
if ((node as DocumentNode).definitions) {
const operationName = getOperationName(node as DocumentNode);
if (operationName) key = phash(`\n# ${operationName}`, key);
let key: HashValue;
if ((node as PersistedDocumentNode).documentId) {
key = phash((node as PersistedDocumentNode).documentId!);
} else {
key = phash(stringifyDocument(node));
// Add the operation name to the produced hash
if ((node as DocumentNode).definitions) {
const operationName = getOperationName(node as DocumentNode);
if (operationName) key = phash(`\n# ${operationName}`, key);
}
}
return key;
};
Expand Down

0 comments on commit e6db80e

Please sign in to comment.