Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prerender: Enable Trusted Documents support #9825

Merged
merged 3 commits into from
Jan 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions packages/prerender/src/graphql/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@ import path from 'path'
import type { DocumentNode } from 'graphql'
import { print } from 'graphql'

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

import { GqlHandlerImportError } from '../errors'

interface GqlOperation {
operationName: string
query: string | undefined
variables?: Record<string, unknown>
extensions?: Record<string, unknown>
}

/**
* Loads the graphql server, with all the user's settings
* And execute the query against it
Expand All @@ -23,8 +30,35 @@ export async function executeQuery(
query: DocumentNode,
variables?: Record<string, unknown>
) {
const config = getConfig()
const operationName = getOperationName(query)
const operation = { operationName, query: print(query), variables }

const operation: GqlOperation = {
operationName,
query: print(query),
variables,
}

// If Trusted Documents support is enabled, we shouldn't send the actual
// query, but rather the hash of the query. We find this hash by looking in
// the generated types file /web/src/graphql/graphql.ts (notice that it's
// generated on the web side)
if (config.graphql.trustedDocuments) {
const documentsPath = path.join(getPaths().web.graphql, 'graphql')
const documents: Record<string, any> | undefined = require(documentsPath)
const documentName =
operationName[0].toUpperCase() + operationName.slice(1) + 'Document'
const queryHash = documents?.[documentName]?.__meta__?.hash

operation.query = undefined
operation.extensions = {
persistedQuery: {
version: 1,
sha256Hash: queryHash,
},
}
}

const handlerResult = await gqlHandler(operation)

return handlerResult?.body
Expand Down
Loading