UNPKG

4.99 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2016, John Hewson
3 * All rights reserved.
4 */
5"use strict";
6/// <reference path="../typings/node.d.ts" />
7/// <reference path="../typings/request.d.ts" />
8/// <reference path="../typings/graphql-utilities.d.ts" />
9/// <reference path="../typings/command-line-args.d.ts" />
10require('source-map-support/register');
11var fs = require('fs');
12var path = require('path');
13var child_process = require('child_process');
14var request = require('request');
15var commandLineArgs = require('command-line-args');
16var utilities_1 = require('graphql/utilities');
17var query_to_elm_1 = require('./query-to-elm');
18// entry point
19var optionDefinitions = [
20 { name: 'init', type: Boolean },
21 { name: 'endpoint', type: String, defaultOption: true },
22 { name: 'schema', type: String },
23 { name: 'method', type: String },
24 { name: 'help', type: Boolean },
25];
26var options = commandLineArgs(optionDefinitions);
27console.log(options);
28// usage
29if (options.help) {
30 usage();
31 process.exit(1);
32}
33if (!options.endpoint) {
34 console.error('Need endpointURL');
35 process.exit(1);
36}
37// output config
38var verb = 'GET';
39var endpointUrl = options.endpoint;
40performIntrospectionQuery(function (body) {
41 var result = JSON.parse(body);
42 var schema = utilities_1.buildClientSchema(result.data);
43 processFiles(schema);
44});
45function performIntrospectionQuery(callback) {
46 // introspection query
47 var introspectionUrl = options.endpoint;
48 if (!introspectionUrl) {
49 console.log('Error: missing graphql endpoint in elm-package.json');
50 process.exit(1);
51 }
52 var method = 'GET';
53 var reqOpts = method == 'GET'
54 ? { url: introspectionUrl,
55 method: method,
56 qs: {
57 query: utilities_1.introspectionQuery.replace(/\n/g, '').replace(/\s+/g, ' ')
58 }
59 }
60 : { url: introspectionUrl,
61 method: method,
62 headers: [{ 'Content-Type': 'application/json' }],
63 body: JSON.stringify({ query: utilities_1.introspectionQuery })
64 };
65 request(reqOpts, function (err, res, body) {
66 if (err) {
67 throw new Error(err);
68 }
69 else if (res.statusCode == 200) {
70 callback(body);
71 }
72 else {
73 console.error('Error', res.statusCode, '-', res.statusMessage);
74 console.error('\n', res.headers);
75 console.error('\n', body.trim());
76 console.error('\nThe GraphQL server at ' + introspectionUrl + ' responded with an error.');
77 process.exit(1);
78 }
79 });
80}
81function capitalize(str) {
82 return str[0].toUpperCase() + str.substr(1);
83}
84function processFiles(schema) {
85 var paths = scanDir('.', []);
86 for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
87 var filePath = paths_1[_i];
88 var fullpath = path.join.apply(path, filePath);
89 var graphql = fs.readFileSync(fullpath, 'utf8');
90 var rootindex = fullpath.indexOf("src/elm/");
91 var rootpath = fullpath.substr(rootindex + 8);
92 var pathdirs = rootpath.split('/');
93 var filepath = pathdirs.map(capitalize).join('.');
94 var basename = path.basename(fullpath);
95 var extname = path.extname(fullpath);
96 var filename = basename.substr(0, basename.length - extname.length);
97 var moduleName = filepath.substr(0, filepath.length - extname.length);
98 var outPath = path.join(path.dirname(fullpath), filename + '.elm');
99 var elm = query_to_elm_1.queryToElm(graphql, moduleName, endpointUrl, verb, schema);
100 fs.writeFileSync(outPath, elm);
101 // if elm-format is available then run it on the output
102 try {
103 child_process.execSync('elm-format "' + outPath + '" --yes');
104 }
105 catch (e) {
106 }
107 }
108 var plural = paths.length != 1 ? 's' : '';
109 console.log('Success! Generated ' + paths.length + ' module' + plural + '.');
110}
111function scanDir(dirpath, parts) {
112 var filenames = fs.readdirSync(dirpath);
113 var found = [];
114 for (var _i = 0, filenames_1 = filenames; _i < filenames_1.length; _i++) {
115 var filename = filenames_1[_i];
116 var fullPath = path.join(dirpath, filename);
117 if (fs.statSync(fullPath).isDirectory() && filename[0] != '.') {
118 found = found.concat(scanDir(fullPath, parts.concat([filename])));
119 }
120 else {
121 if (path.extname(filename) == '.graphql') {
122 found.push(parts.concat(filename));
123 }
124 }
125 }
126 return found;
127}
128function usage() {
129 var version = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8')).version;
130 console.error('elm-graphql ' + version);
131 console.error();
132 console.error('Usage: elm graphql --init ENDPOINT-URL');
133 console.error(' ');
134 console.error('Available options:');
135 console.error(' --schema URL URL of the schema endpoint, if different.');
136}
137//# sourceMappingURL=main.js.map
\No newline at end of file