Skip to content

Commit

Permalink
Add support for endpoints with existing query params
Browse files Browse the repository at this point in the history
  • Loading branch information
airhorns committed Nov 16, 2023
1 parent d68d46c commit a344473
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
33 changes: 33 additions & 0 deletions packages/api-client-core/spec/GadgetConnection-suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,39 @@ export const GadgetConnectionSharedSuite = (queryExtra = "") => {
expect((connection as any).requestPolicy).toEqual("network-only");
});

it("should allow connecting to an endpoint with existing query params", async () => {
nock("https://someapp.gadget.app")
.post("/api/graphql?foo=bar&operation=meta", { query: `{\n meta {\n appName\n${queryExtra} }\n}`, variables: {} })
.reply(200, {
data: {
meta: {
appName: "some app",
},
},
});

const connection = new GadgetConnection({
endpoint: "https://someapp.gadget.app/api/graphql?foo=bar",
authenticationMode: { anonymous: true },
});

const result = await connection.currentClient
.query(
gql`
{
meta {
appName
}
}
`,
{}
)
.toPromise();

expect(result.error).toBeUndefined();
expect(result.data).toEqual({ meta: { appName: "some app" } });
});

describe("authorization", () => {
it("should allow connecting with anonymous authentication", async () => {
nock("https://someapp.gadget.app")
Expand Down
11 changes: 9 additions & 2 deletions packages/api-client-core/src/exchanges/urlParamExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@ import { mapExchange } from "@urql/core";

export const urlParamExchange = mapExchange({
onOperation: (operation) => {
if (operation.context.url && operation.context.operationName && !operation.context.url.includes("?")) {
operation.context.url += `?operation=${operation.context.operationName}`;
if (operation.context.url && operation.context.operationName) {
try {
const [start, params] = operation.context.url.split("?");
const paramsObj = new URLSearchParams(params);
paramsObj.set("operation", operation.context.operationName);
operation.context.url = `${start}?${paramsObj.toString()}`;
} catch (error) {
// not able to parse URL params, just don't add this optional param and let the rest of the system react to the invalid URL
}
}
},
});

0 comments on commit a344473

Please sign in to comment.