Skip to content

Commit

Permalink
fix: return GraphQLError when no valid documentId
Browse files Browse the repository at this point in the history
  • Loading branch information
mvantellingen committed Jan 21, 2025
1 parent 47941ff commit 4e0475a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/lemon-houses-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/apollo-trusted-documents": patch
---

Return GraphQL error when document id is required and missing
1 change: 1 addition & 0 deletions biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"noUnusedVariables": "off"
},
"suspicious": {
"noConfusingVoidType": "off",
"noConsoleLog": "error",
"noEvolvingTypes": "error",
"noExplicitAny": "warn",
Expand Down
28 changes: 19 additions & 9 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type {
ApolloServerPlugin,
BaseContext,
GraphQLRequestContext,
GraphQLRequestContextDidResolveSource,
GraphQLRequestListener,
} from "@apollo/server";
import { GraphQLError } from "graphql";
import type { DocumentStore } from "./store-base";
Expand Down Expand Up @@ -30,7 +32,7 @@ export class TrustedDocumentsPlugin<TContext extends BaseContext>

public async requestDidStart(
requestContext: GraphQLRequestContext<TContext>,
): Promise<void> {
): Promise<void | GraphQLRequestListener<TContext>> {
const { request } = requestContext;
let documentId: string | undefined;

Expand Down Expand Up @@ -78,23 +80,31 @@ export class TrustedDocumentsPlugin<TContext extends BaseContext>
}
}

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<TContext>,
) => {
if (documentId) {
throw new GraphQLError("No document found for documentId");
}
throw new GraphQLError("This operation requires a valid documentId");
},
};
}
}
}

0 comments on commit 4e0475a

Please sign in to comment.