-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
67 lines (59 loc) · 1.52 KB
/
utils.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
export function mergeHeaders(
a?: HeadersInit,
b?: HeadersInit,
): [data: HeadersInit, err: undefined] | [data: undefined, err: TypeError] {
const aHeader = new Headers(a);
const bHeader = new Headers(b);
try {
aHeader.forEach((value, key) => {
bHeader.append(key, value);
});
const headersInit = Object.fromEntries(bHeader.entries());
return [headersInit ?? {}, undefined];
} catch (e) {
return [, e as TypeError];
}
}
export function mergeInit<
T extends { headers?: HeadersInit },
>(
a: T,
b: T,
): [data: T] | [data: undefined, err: TypeError] {
const [headers, err] = mergeHeaders(a.headers, b.headers);
if (err) {
return [, err];
}
return [{
...a,
...b,
headers,
}];
}
/** Compress GraphQL query.
* @param query Graphql query.
* ```ts
* import { gql } from "https://deno.land/x/graphql_http@$VERSION/mod.ts";
* import { assertEquals } from "https://deno.land/std@$VERSION/testing/asserts.ts";
*
* const query = gql`query Test {
* hello
* }`;
* assertEquals(query, "query Test{hello}");
* ```
*/
export function gql(query: TemplateStringsArray): string {
return query.reduce((acc, cur) => `${acc}${cleanQuery(cur)}`, "");
}
function cleanQuery(query: string): string {
return query
// remove multiple whitespace
.replace(/\s+/g, " ")
// remove all whitespace between everything except for word and word boundaries
.replace(/(\B)\s(\B)|(\b)\s(\B)|(\B)\s(\b)/gm, "")
.trim();
}
const query = gql`query Test {
hello
}`;
console.log(query);