Last active
February 2, 2022 07:40
-
-
Save Cerberus/a06ab5389f032508b96955fd20de5ef3 to your computer and use it in GitHub Desktop.
A simple way to generate query-hash for `apollo client:extract`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { defaultOperationRegistrySignature, operationHash } from 'apollo-graphql/lib/operationId' | |
const persistedLink = createPersistedQueryLink({ | |
generateHash: (document) => { | |
const operationName = document.definitions.find( | |
(definition) => definition.kind === 'OperationDefinition', | |
// @ts-ignore | |
)!.name.value | |
const printed = defaultOperationRegistrySignature(document, operationName) | |
return operationHash(printed) | |
}, | |
}) | |
// Trade off: | |
// - Spend more cpu time 3-15 ms for creating hash. (depend on string length) | |
// - Additional Chunk size 40KB GZip. (by apollo-graphql package) | |
// Ref: https://github.com/apollographql/apollo-client/issues/7032 | |
/* | |
// Note: If you are using V8 (e.g. cloudflare worker). You can replace `operationHash` with this custom function. | |
const toHex = (hashBuffer: ArrayBuffer) => { | |
const hashArray = Array.from(new Uint8Array(hashBuffer)) | |
return hashArray.map((b) => `00${b.toString(16)}`.slice(-2)).join('') | |
} | |
const operationHash = async (message: string) => { | |
const msgBuffer = new TextEncoder().encode(message) | |
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer) | |
const result = toHex(hashBuffer) | |
return result | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment