From 4e0475a549b3d8a86e162b76694f9b9956f34d03 Mon Sep 17 00:00:00 2001 From: Michael van Tellingen Date: Tue, 21 Jan 2025 19:44:46 +0100 Subject: [PATCH] fix: return GraphQLError when no valid documentId --- .changeset/lemon-houses-bathe.md | 5 +++++ biome.jsonc | 1 + src/plugin.ts | 28 +++++++++++++++++++--------- 3 files changed, 25 insertions(+), 9 deletions(-) create mode 100644 .changeset/lemon-houses-bathe.md diff --git a/.changeset/lemon-houses-bathe.md b/.changeset/lemon-houses-bathe.md new file mode 100644 index 0000000..0c5052f --- /dev/null +++ b/.changeset/lemon-houses-bathe.md @@ -0,0 +1,5 @@ +--- +"@labdigital/apollo-trusted-documents": patch +--- + +Return GraphQL error when document id is required and missing diff --git a/biome.jsonc b/biome.jsonc index d5e4283..55e5ec1 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -27,6 +27,7 @@ "noUnusedVariables": "off" }, "suspicious": { + "noConfusingVoidType": "off", "noConsoleLog": "error", "noEvolvingTypes": "error", "noExplicitAny": "warn", diff --git a/src/plugin.ts b/src/plugin.ts index 6b0b236..345eac6 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -3,6 +3,8 @@ import type { ApolloServerPlugin, BaseContext, GraphQLRequestContext, + GraphQLRequestContextDidResolveSource, + GraphQLRequestListener, } from "@apollo/server"; import { GraphQLError } from "graphql"; import type { DocumentStore } from "./store-base"; @@ -30,7 +32,7 @@ export class TrustedDocumentsPlugin public async requestDidStart( requestContext: GraphQLRequestContext, - ): Promise { + ): Promise> { const { request } = requestContext; let documentId: string | undefined; @@ -78,23 +80,31 @@ export class TrustedDocumentsPlugin } } + let didResolveDocument = false; + if (documentId) { const query = await this.options.store.get(documentId); - if (!query) { - if (this.options.strict) { - throw new GraphQLError("No persisted query found"); - } else { - console.error("No persisted query found for documentId", documentId); - } - } - if (query) { + didResolveDocument = true; request.query = query; if (request.extensions?.persistedQuery) { request.extensions.persistedQuery = undefined; } } } + + if (!didResolveDocument && this.options.strict) { + return { + didResolveOperation: ( + requestContext: GraphQLRequestContextDidResolveSource, + ) => { + if (documentId) { + throw new GraphQLError("No document found for documentId"); + } + throw new GraphQLError("This operation requires a valid documentId"); + }, + }; + } } }