UNPKG

2.25 kBJavaScriptView Raw
1import { serializeFetchParameter } from "./serializeFetchParameter.js";
2// For GET operations, returns the given URI rewritten with parameters, or a
3// parse error.
4export function rewriteURIForGET(chosenURI, body) {
5 // Implement the standard HTTP GET serialization, plus 'extensions'. Note
6 // the extra level of JSON serialization!
7 var queryParams = [];
8 var addQueryParam = function (key, value) {
9 queryParams.push("".concat(key, "=").concat(encodeURIComponent(value)));
10 };
11 if ("query" in body) {
12 addQueryParam("query", body.query);
13 }
14 if (body.operationName) {
15 addQueryParam("operationName", body.operationName);
16 }
17 if (body.variables) {
18 var serializedVariables = void 0;
19 try {
20 serializedVariables = serializeFetchParameter(body.variables, "Variables map");
21 }
22 catch (parseError) {
23 return { parseError: parseError };
24 }
25 addQueryParam("variables", serializedVariables);
26 }
27 if (body.extensions) {
28 var serializedExtensions = void 0;
29 try {
30 serializedExtensions = serializeFetchParameter(body.extensions, "Extensions map");
31 }
32 catch (parseError) {
33 return { parseError: parseError };
34 }
35 addQueryParam("extensions", serializedExtensions);
36 }
37 // Reconstruct the URI with added query params.
38 // XXX This assumes that the URI is well-formed and that it doesn't
39 // already contain any of these query params. We could instead use the
40 // URL API and take a polyfill (whatwg-url@6) for older browsers that
41 // don't support URLSearchParams. Note that some browsers (and
42 // versions of whatwg-url) support URL but not URLSearchParams!
43 var fragment = "", preFragment = chosenURI;
44 var fragmentStart = chosenURI.indexOf("#");
45 if (fragmentStart !== -1) {
46 fragment = chosenURI.substr(fragmentStart);
47 preFragment = chosenURI.substr(0, fragmentStart);
48 }
49 var queryParamsPrefix = preFragment.indexOf("?") === -1 ? "?" : "&";
50 var newURI = preFragment + queryParamsPrefix + queryParams.join("&") + fragment;
51 return { newURI: newURI };
52}
53//# sourceMappingURL=rewriteURIForGET.js.map
\No newline at end of file