1 | 'use strict';
|
2 |
|
3 | const fetch = require("node-fetch");
|
4 | const fs = require("fs");
|
5 |
|
6 | const {
|
7 | buildClientSchema,
|
8 | introspectionQuery,
|
9 | printSchema
|
10 | } = require("graphql/utilities");
|
11 | const chalk = require("chalk");
|
12 |
|
13 | function isURL(str) {
|
14 | const urlRegex =
|
15 | "^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost|django)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$";
|
16 | const url = new RegExp(urlRegex, "i");
|
17 | return str.length < 2083 && url.test(str)
|
18 | }
|
19 |
|
20 | const url = process.argv[3];
|
21 |
|
22 | const saveJson = process.argv[4] === 'json';
|
23 |
|
24 | if (!url) {
|
25 | console.log("Usage: get-schema " + chalk.green("url"));
|
26 | console.log(" " + chalk.green("url") + " is your graphql server address");
|
27 | process.exit()
|
28 | }
|
29 |
|
30 | if (!isURL(url)) {
|
31 | console.log(chalk.red(url) + " is not a valid url");
|
32 | process.exit(1)
|
33 | }
|
34 |
|
35 | console.log("Downloading for url: " + chalk.green(url));
|
36 |
|
37 | fetch(url, {
|
38 | method: "POST",
|
39 | headers: {
|
40 | Accept: "application/json",
|
41 | "Content-Type": "application/json"
|
42 | },
|
43 | body: JSON.stringify({query: introspectionQuery})
|
44 | })
|
45 | .then(res => res.json())
|
46 | .then(res => {
|
47 | console.log(res);
|
48 | console.log("schema.graphql has downloaded and saved");
|
49 | if (saveJson) {
|
50 | const jsonString = JSON.stringify(res.data);
|
51 | console.log("schema.json has been saved");
|
52 | fs.writeFileSync("schema.json", jsonString)
|
53 | }
|
54 | const schemaString = printSchema(buildClientSchema(res.data));
|
55 | fs.writeFileSync("schema.graphql", schemaString)
|
56 | })
|
57 | .catch(e => {
|
58 | console.log(chalk.red("\nError:"));
|
59 | console.error(e);
|
60 | process.exit(1)
|
61 | });
|