From 1c35bcfbce587b06244b060abd82f55c2e9211df Mon Sep 17 00:00:00 2001 From: Phil Pluckthun Date: Sun, 28 Apr 2024 13:27:34 +0100 Subject: [PATCH] fix(core): Use documentId for operation hash if it's available (#3575) --- .changeset/forty-walls-hug.md | 5 +++++ packages/core/src/utils/request.test.ts | 10 ++++++++++ packages/core/src/utils/request.ts | 19 ++++++++++++++----- 3 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 .changeset/forty-walls-hug.md diff --git a/.changeset/forty-walls-hug.md b/.changeset/forty-walls-hug.md new file mode 100644 index 00000000..a6885bbb --- /dev/null +++ b/.changeset/forty-walls-hug.md @@ -0,0 +1,5 @@ +--- +'@urql/core': patch +--- + +Use `documentId` from persisted documents for document keys, when it's available. diff --git a/packages/core/src/utils/request.test.ts b/packages/core/src/utils/request.test.ts index 9373ff80..f6079f9f 100644 --- a/packages/core/src/utils/request.test.ts +++ b/packages/core/src/utils/request.test.ts @@ -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 ', () => { diff --git a/packages/core/src/utils/request.ts b/packages/core/src/utils/request.ts index 110e5914..eba0ac9b 100644 --- a/packages/core/src/utils/request.ts +++ b/packages/core/src/utils/request.ts @@ -12,6 +12,10 @@ import type { RequestExtensions, } from '../types'; +type PersistedDocumentNode = TypedDocumentNode & { + documentId?: string; +}; + /** A `DocumentNode` annotated with its hashed key. * @internal */ @@ -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; }; -- knotmirror 0.0.1