Skip to content

Commit

Permalink
feat: add support for non-strict mode (dry-run)
Browse files Browse the repository at this point in the history
This mode allows queries which contain both a documentId and a query
  • Loading branch information
mvantellingen committed Jan 21, 2025
1 parent 4ccc0e0 commit 47941ff
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/sour-toys-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/apollo-trusted-documents": patch
---

Support both documentId and query in the same request (non-strict)
37 changes: 30 additions & 7 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import type { DocumentStore } from "./store-base";

type PluginOptions = {
store?: DocumentStore;
strict?: boolean;
bypassSecret?: string;
bypassHeader?: string;
};

const pluginDefaults: Partial<PluginOptions> = {
bypassHeader: "x-bypass-trusted-operations",
strict: true,
};

export class TrustedDocumentsPlugin<TContext extends BaseContext>
Expand Down Expand Up @@ -45,10 +47,20 @@ export class TrustedDocumentsPlugin<TContext extends BaseContext>

// 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<string, unknown>;
};

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
Expand All @@ -58,19 +70,30 @@ export class TrustedDocumentsPlugin<TContext extends BaseContext>
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);
}
}

if (documentId) {
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;
}
}
}
}
Expand Down

0 comments on commit 47941ff

Please sign in to comment.