Skip to content

Commit 7549766

Browse files
authored
Merge pull request #300 from gadget-inc/operation-exchange-adds-params
Add support for endpoints with existing query params
2 parents d68d46c + 15b7915 commit 7549766

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

packages/api-client-core/spec/GadgetConnection-suite.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,39 @@ export const GadgetConnectionSharedSuite = (queryExtra = "") => {
3535
expect((connection as any).requestPolicy).toEqual("network-only");
3636
});
3737

38+
it("should allow connecting to an endpoint with existing query params", async () => {
39+
nock("https://someapp.gadget.app")
40+
.post("/api/graphql?foo=bar&operation=meta", { query: `{\n meta {\n appName\n${queryExtra} }\n}`, variables: {} })
41+
.reply(200, {
42+
data: {
43+
meta: {
44+
appName: "some app",
45+
},
46+
},
47+
});
48+
49+
const connection = new GadgetConnection({
50+
endpoint: "https://someapp.gadget.app/api/graphql?foo=bar",
51+
authenticationMode: { anonymous: true },
52+
});
53+
54+
const result = await connection.currentClient
55+
.query(
56+
gql`
57+
{
58+
meta {
59+
appName
60+
}
61+
}
62+
`,
63+
{}
64+
)
65+
.toPromise();
66+
67+
expect(result.error).toBeUndefined();
68+
expect(result.data).toEqual({ meta: { appName: "some app" } });
69+
});
70+
3871
describe("authorization", () => {
3972
it("should allow connecting with anonymous authentication", async () => {
4073
nock("https://someapp.gadget.app")

packages/api-client-core/src/exchanges/urlParamExchange.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,15 @@ import { mapExchange } from "@urql/core";
22

33
export const urlParamExchange = mapExchange({
44
onOperation: (operation) => {
5-
if (operation.context.url && operation.context.operationName && !operation.context.url.includes("?")) {
6-
operation.context.url += `?operation=${operation.context.operationName}`;
5+
if (operation.context.url && operation.context.operationName) {
6+
try {
7+
const [start, params] = operation.context.url.split("?");
8+
const paramsObj = new URLSearchParams(params);
9+
paramsObj.set("operation", operation.context.operationName);
10+
operation.context.url = `${start}?${paramsObj.toString()}`;
11+
} catch (error) {
12+
// 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
13+
}
714
}
815
},
916
});

0 commit comments

Comments
 (0)