-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathrewriteURIForGET.ts
More file actions
55 lines (52 loc) · 1.93 KB
/
Copy pathrewriteURIForGET.ts
File metadata and controls
55 lines (52 loc) · 1.93 KB
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
import type { HttpLink } from "./HttpLink.js";
// For GET operations, returns the given URI rewritten with parameters, or a
// parse error.
export function rewriteURIForGET(chosenURI: string, body: HttpLink.Body) {
// Implement the standard HTTP GET serialization, plus 'extensions'. Note
// the extra level of JSON serialization!
const queryParams: string[] = [];
const addQueryParam = (key: string, value: string) => {
queryParams.push(`${key}=${encodeURIComponent(value)}`);
};
if ("query" in body) {
addQueryParam("query", body.query!);
}
if (body.operationName) {
addQueryParam("operationName", body.operationName);
}
if (body.variables) {
let serializedVariables;
try {
serializedVariables = JSON.stringify(body.variables);
} catch (parseError) {
return { parseError };
}
addQueryParam("variables", serializedVariables);
}
if (body.extensions) {
let serializedExtensions;
try {
serializedExtensions = JSON.stringify(body.extensions);
} catch (parseError) {
return { parseError };
}
addQueryParam("extensions", serializedExtensions);
}
// Reconstruct the URI with added query params.
// XXX This assumes that the URI is well-formed and that it doesn't
// already contain any of these query params. We could instead use the
// URL API and take a polyfill (whatwg-url@6) for older browsers that
// don't support URLSearchParams. Note that some browsers (and
// versions of whatwg-url) support URL but not URLSearchParams!
let fragment = "",
preFragment = chosenURI;
const fragmentStart = chosenURI.indexOf("#");
if (fragmentStart !== -1) {
fragment = chosenURI.substr(fragmentStart);
preFragment = chosenURI.substr(0, fragmentStart);
}
const queryParamsPrefix = preFragment.indexOf("?") === -1 ? "?" : "&";
const newURI =
preFragment + queryParamsPrefix + queryParams.join("&") + fragment;
return { newURI };
}