-
Notifications
You must be signed in to change notification settings - Fork 85
/
graphql.ts
90 lines (76 loc) · 2.4 KB
/
graphql.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { request as Request } from "@octokit/request";
import type { ResponseHeaders } from "@octokit/types";
import { GraphqlResponseError } from "./error.js";
import type {
GraphQlEndpointOptions,
RequestParameters,
GraphQlQueryResponse,
GraphQlQueryResponseData,
} from "./types.js";
const NON_VARIABLE_OPTIONS = [
"method",
"baseUrl",
"url",
"headers",
"request",
"query",
"mediaType",
];
const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
export function graphql<ResponseData = GraphQlQueryResponseData>(
request: typeof Request,
query: string | RequestParameters,
options?: RequestParameters,
): Promise<ResponseData> {
if (options) {
if (typeof query === "string" && "query" in options) {
return Promise.reject(
new Error(`[@octokit/graphql] "query" cannot be used as variable name`),
);
}
for (const key in options) {
if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
return Promise.reject(
new Error(
`[@octokit/graphql] "${key}" cannot be used as variable name`,
),
);
}
}
const parsedOptions =
typeof query === "string" ? Object.assign({ query }, options) : query;
const requestOptions = Object.keys(
parsedOptions,
).reduce<GraphQlEndpointOptions>((result, key) => {
if (NON_VARIABLE_OPTIONS.includes(key)) {
result[key] = parsedOptions[key];
return result;
}
if (!result.variables) {
result.variables = {};
}
result.variables[key] = parsedOptions[key];
return result;
}, {} as GraphQlEndpointOptions);
// workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
// https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
}
return request(requestOptions).then((response) => {
if (response.data.errors) {
const headers: ResponseHeaders = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlResponseError(
requestOptions,
headers,
response.data as Required<GraphQlQueryResponse<ResponseData>>,
);
}
return response.data.data;
});
}