Skip to content

Commit 8e15940

Browse files
authored
fix: throw helpful error in case "query", "url", or "method" is used as query variable (#265)
1 parent cc3ec32 commit 8e15940

File tree

2 files changed

+56
-4
lines changed

2 files changed

+56
-4
lines changed

src/graphql.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,29 @@ const NON_VARIABLE_OPTIONS = [
1818
"mediaType",
1919
];
2020

21+
const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
22+
2123
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
2224

2325
export function graphql<ResponseData = GraphQlQueryResponseData>(
2426
request: typeof Request,
2527
query: string | RequestParameters,
2628
options?: RequestParameters
2729
): Promise<ResponseData> {
28-
if (typeof query === "string" && options && "query" in options) {
29-
return Promise.reject(
30-
new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
31-
);
30+
if (options) {
31+
if (typeof query === "string" && "query" in options) {
32+
return Promise.reject(
33+
new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
34+
);
35+
}
36+
37+
for (const key in options) {
38+
if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
39+
40+
return Promise.reject(
41+
new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`)
42+
);
43+
}
3244
}
3345

3446
const parsedOptions =

test/graphql.test.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,4 +231,44 @@ describe("graphql()", () => {
231231
);
232232
});
233233
});
234+
235+
it("url variable (#264)", () => {
236+
expect.assertions(1);
237+
238+
const query = `query GetCommitStatus($url: URI!) {
239+
resource(url: $url) {
240+
... on Commit {
241+
status {
242+
state
243+
}
244+
}
245+
}
246+
}`;
247+
248+
return graphql(query, {
249+
url: "https://example.com",
250+
}).catch((error) => {
251+
expect(error.message).toEqual(
252+
`[@octokit/graphql] "url" cannot be used as variable name`
253+
);
254+
});
255+
});
256+
257+
it("method variable", () => {
258+
expect.assertions(1);
259+
260+
const query = `query($method:String!){
261+
search(query:$method,type:ISSUE) {
262+
codeCount
263+
}
264+
}`;
265+
266+
return graphql(query, {
267+
method: "test",
268+
}).catch((error) => {
269+
expect(error.message).toEqual(
270+
`[@octokit/graphql] "method" cannot be used as variable name`
271+
);
272+
});
273+
});
234274
});

0 commit comments

Comments
 (0)