From 47941ffc9e335080cc10c94c528fde3ea6fe6ded Mon Sep 17 00:00:00 2001 From: Michael van Tellingen Date: Tue, 21 Jan 2025 14:58:26 +0100 Subject: [PATCH] feat: add support for non-strict mode (dry-run) This mode allows queries which contain both a documentId and a query --- .changeset/sour-toys-push.md | 5 +++++ src/plugin.ts | 37 +++++++++++++++++++++++++++++------- 2 files changed, 35 insertions(+), 7 deletions(-) create mode 100644 .changeset/sour-toys-push.md diff --git a/.changeset/sour-toys-push.md b/.changeset/sour-toys-push.md new file mode 100644 index 0000000..be455d5 --- /dev/null +++ b/.changeset/sour-toys-push.md @@ -0,0 +1,5 @@ +--- +"@labdigital/apollo-trusted-documents": patch +--- + +Support both documentId and query in the same request (non-strict) diff --git a/src/plugin.ts b/src/plugin.ts index 24ca0a3..6b0b236 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -9,12 +9,14 @@ import type { DocumentStore } from "./store-base"; type PluginOptions = { store?: DocumentStore; + strict?: boolean; bypassSecret?: string; bypassHeader?: string; }; const pluginDefaults: Partial = { bypassHeader: "x-bypass-trusted-operations", + strict: true, }; export class TrustedDocumentsPlugin @@ -45,10 +47,20 @@ export class TrustedDocumentsPlugin // IF POST, extract from body if (request.http?.method === "POST") { - const body = request.http?.body as { documentId?: string }; - documentId = body.documentId; + const body = request.http?.body as { + documentId?: string; + extensions?: Record; + }; - body.documentId = undefined; + // If we have a documentId we use that and remove the + // extensions.persistedQueries as this only causes confusion downstream + if (body.documentId) { + documentId = body.documentId; + body.documentId = undefined; + if (body.extensions?.persistedQuery) { + body.extensions.persistedQuery = undefined; + } + } } // IF GET, extract from search params @@ -58,6 +70,11 @@ export class TrustedDocumentsPlugin documentId = Array.isArray(qs.documentId) ? qs.documentId[0] : qs.documentId; + + // Remove the documentId and extensions from the query string + qs.documentId = undefined; + qs.extensions = undefined; + request.http.search = "?" + querystring.stringify(qs); } } @@ -65,12 +82,18 @@ export class TrustedDocumentsPlugin const query = await this.options.store.get(documentId); if (!query) { - throw new GraphQLError("No persisted query found"); + if (this.options.strict) { + throw new GraphQLError("No persisted query found"); + } else { + console.error("No persisted query found for documentId", documentId); + } } - request.query = query; - if (request.extensions?.persistedQueries) { - request.extensions.persistedQueries = undefined; + if (query) { + request.query = query; + if (request.extensions?.persistedQuery) { + request.extensions.persistedQuery = undefined; + } } } }