-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
93 lines (86 loc) · 2.08 KB
/
lib.js
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
91
92
93
import fetch from "node-fetch";
import fs from "fs";
import path from "path";
import {
introspectionQuery,
buildClientSchema,
printSchema,
} from "graphql/utilities/index.js";
import * as query from "querystringify";
/**
*
* Normalizes header input from CLI
*
* @param cli
*/
export function getHeadersFromInput(cli) {
switch (typeof cli.flags.header) {
case "string": {
const keys = query.parse(cli.flags.header);
const key = Object.keys(keys)[0];
return [{ key: key, value: keys[key] }];
}
case "object": {
return cli.flags.header.map((header) => {
const keys = query.parse(header);
const key = Object.keys(keys)[0];
return { key: key, value: keys[key] };
});
}
default: {
return [];
}
}
}
/**
*
* Fetch remote schema and turn it into string
*
* @param endpoint
* @param options
*/
export async function getRemoteSchema(endpoint, options) {
try {
const { data, errors } = await fetch(endpoint, {
method: options.method,
headers: options.headers,
body: JSON.stringify({ query: introspectionQuery }),
}).then((res) => res.json());
if (errors) {
return { status: "err", message: JSON.stringify(errors, null, 2) };
}
if (options.json) {
return {
status: "ok",
schema: JSON.stringify(data, null, 2),
};
} else {
const schema = buildClientSchema(data);
return {
status: "ok",
schema: printSchema(schema),
};
}
} catch (err) {
return { status: "err", message: err.message };
}
}
/**
*
* Prints schema to file.
*
* @param dist
* @param schema
*/
export function printToFile(dist, schema) {
try {
const output = path.resolve(process.cwd(), dist);
if (!fs.existsSync(output)) {
fs.mkdirSync(output);
}
fs.writeFileSync(path.join(output, `shema.graphql`), schema);
return { status: "ok", path: output };
} catch (err) {
return { status: "err", message: err.message };
}
}