Skip to content

Commit b18d9cd

Browse files
authored
prerender: Enable Trusted Documents support (#9825)
1 parent e5421c3 commit b18d9cd

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

packages/prerender/src/graphql/graphql.ts

+36-2
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,19 @@ import path from 'path'
33
import type { DocumentNode } from 'graphql'
44
import { print } from 'graphql'
55

6-
import { getPaths } from '@redwoodjs/project-config'
6+
import { getConfig, getPaths } from '@redwoodjs/project-config'
77
// @MARK: have to do this, otherwise rwjs/web is loaded before shims
88
import { getOperationName } from '@redwoodjs/web/dist/graphql'
99

1010
import { GqlHandlerImportError } from '../errors'
1111

12+
interface GqlOperation {
13+
operationName: string
14+
query: string | undefined
15+
variables?: Record<string, unknown>
16+
extensions?: Record<string, unknown>
17+
}
18+
1219
/**
1320
* Loads the graphql server, with all the user's settings
1421
* And execute the query against it
@@ -23,8 +30,35 @@ export async function executeQuery(
2330
query: DocumentNode,
2431
variables?: Record<string, unknown>
2532
) {
33+
const config = getConfig()
2634
const operationName = getOperationName(query)
27-
const operation = { operationName, query: print(query), variables }
35+
36+
const operation: GqlOperation = {
37+
operationName,
38+
query: print(query),
39+
variables,
40+
}
41+
42+
// If Trusted Documents support is enabled, we shouldn't send the actual
43+
// query, but rather the hash of the query. We find this hash by looking in
44+
// the generated types file /web/src/graphql/graphql.ts (notice that it's
45+
// generated on the web side)
46+
if (config.graphql.trustedDocuments) {
47+
const documentsPath = path.join(getPaths().web.graphql, 'graphql')
48+
const documents: Record<string, any> | undefined = require(documentsPath)
49+
const documentName =
50+
operationName[0].toUpperCase() + operationName.slice(1) + 'Document'
51+
const queryHash = documents?.[documentName]?.__meta__?.hash
52+
53+
operation.query = undefined
54+
operation.extensions = {
55+
persistedQuery: {
56+
version: 1,
57+
sha256Hash: queryHash,
58+
},
59+
}
60+
}
61+
2862
const handlerResult = await gqlHandler(operation)
2963

3064
return handlerResult?.body

0 commit comments

Comments
 (0)