UNPKG

12.5 kBJavaScriptView Raw
1"use strict";
2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3 return new (P || (P = Promise))(function (resolve, reject) {
4 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7 step((generator = generator.apply(thisArg, _arguments || [])).next());
8 });
9};
10var __generator = (this && this.__generator) || function (thisArg, body) {
11 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13 function verb(n) { return function (v) { return step([n, v]); }; }
14 function step(op) {
15 if (f) throw new TypeError("Generator is already executing.");
16 while (_) try {
17 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18 if (y = 0, t) op = [op[0] & 2, t.value];
19 switch (op[0]) {
20 case 0: case 1: t = op; break;
21 case 4: _.label++; return { value: op[1], done: false };
22 case 5: _.label++; y = op[1]; op = [0]; continue;
23 case 7: op = _.ops.pop(); _.trys.pop(); continue;
24 default:
25 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29 if (t[2]) _.ops.pop();
30 _.trys.pop(); continue;
31 }
32 op = body.call(thisArg, _);
33 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35 }
36};
37Object.defineProperty(exports, "__esModule", { value: true });
38var inquirer = require("inquirer");
39var chalk_1 = require("chalk");
40var path_1 = require("path");
41var fs_1 = require("fs");
42var YAML = require("json-to-pretty-yaml");
43var detectIndent = require("detect-indent");
44var Tags;
45(function (Tags) {
46 Tags["client"] = "Client";
47 Tags["server"] = "Server";
48 Tags["typescript"] = "TypeScript";
49 Tags["angular"] = "Angular";
50 Tags["react"] = "React";
51 Tags["mongodb"] = "MongoDB";
52})(Tags || (Tags = {}));
53function log() {
54 var msgs = [];
55 for (var _i = 0; _i < arguments.length; _i++) {
56 msgs[_i] = arguments[_i];
57 }
58 // tslint:disable-next-line
59 console.log.apply(console, msgs);
60}
61var plugins = [
62 {
63 name: "TypeScript Common " + chalk_1.default.italic('(required by client and server plugins)'),
64 package: 'graphql-codegen-typescript-common',
65 value: 'typescript-common',
66 tags: [Tags.typescript, Tags.client, Tags.server]
67 },
68 {
69 name: "TypeScript Client " + chalk_1.default.italic('(operations and fragments)'),
70 package: 'graphql-codegen-typescript-client',
71 value: 'typescript-client',
72 tags: [Tags.typescript, Tags.client]
73 },
74 {
75 name: "TypeScript Server " + chalk_1.default.italic('(GraphQL Schema)'),
76 package: 'graphql-codegen-typescript-server',
77 value: 'typescript-server',
78 tags: [Tags.typescript, Tags.client, Tags.server]
79 },
80 {
81 name: "TypeScript Resolvers " + chalk_1.default.italic('(strongly typed resolve functions)'),
82 package: 'graphql-codegen-typescript-resolvers',
83 value: 'typescript-resolvers',
84 tags: [Tags.typescript, Tags.server]
85 },
86 {
87 name: "TypeScript Apollo Angular " + chalk_1.default.italic('(GQL services)'),
88 package: 'graphql-codegen-typescript-apollo-angular',
89 value: 'typescript-apollo-angular',
90 tags: [Tags.typescript, Tags.angular, Tags.client]
91 },
92 {
93 name: "TypeScript React Apollo " + chalk_1.default.italic('(typed components and HOCs)'),
94 package: 'graphql-codegen-typescript-react-apollo',
95 value: 'typescript-react-apollo',
96 tags: [Tags.typescript, Tags.react, Tags.client]
97 },
98 {
99 name: "TypeScript MongoDB " + chalk_1.default.italic('(typed MongoDB objects)'),
100 package: 'graphql-codegen-typescript-mongodb',
101 value: 'typescript-mongodb',
102 tags: [Tags.typescript, Tags.mongodb, Tags.server]
103 },
104 {
105 name: "TypeScript GraphQL files modules " + chalk_1.default.italic('(declarations for .graphql files)'),
106 package: 'graphql-codegen-graphql-files-modules',
107 value: 'typescript-graphql-files-modules',
108 tags: [Tags.typescript, Tags.client]
109 }
110];
111var targets = [Tags.client, Tags.server];
112function init() {
113 return __awaiter(this, void 0, void 0, function () {
114 var _a, answers, config, relativePath;
115 return __generator(this, function (_b) {
116 switch (_b.label) {
117 case 0:
118 log("\n Welcome to " + chalk_1.default.bold('GraphQL Code Generator') + "!\n Answer few questions and we will setup everything for you.\n ");
119 return [4 /*yield*/, inquirer.prompt([
120 {
121 type: 'list',
122 name: 'target',
123 message: 'What is your target?',
124 choices: targets
125 },
126 {
127 type: 'input',
128 name: 'schema',
129 message: 'How can I access the schema?:',
130 suffix: chalk_1.default.grey(' (path or url)'),
131 default: 'https://localhost:4000',
132 validate: function (str) { return str.length > 0; }
133 },
134 {
135 type: 'input',
136 name: 'documents',
137 message: 'Where can I find operations and fragments?:',
138 when: function (answers) { return answers.target === Tags.client; },
139 default: '**/*.graphql',
140 validate: function (str) { return str.length > 0; }
141 },
142 {
143 type: 'checkbox',
144 name: 'plugins',
145 message: 'Pick plugins:',
146 choices: function (answers) {
147 return plugins
148 .filter(function (p) { return p.tags.includes(answers.target); })
149 .map(function (p) {
150 return {
151 name: p.name,
152 value: p
153 };
154 });
155 },
156 validate: function (plugins) { return plugins.length > 0; }
157 },
158 {
159 type: 'input',
160 name: 'output',
161 message: 'Where to write the output:',
162 default: 'src/generated/graphql.ts',
163 validate: function (str) { return str.length > 0; }
164 },
165 {
166 type: 'confirm',
167 name: 'introspection',
168 message: 'Do you want to generate an introspection file?'
169 },
170 {
171 type: 'input',
172 name: 'config',
173 message: 'How to name the config file?',
174 default: 'codegen.yml',
175 validate: function (str) {
176 var isNotEmpty = str.length > 0;
177 var hasCorrectExtension = ['json', 'yml', 'yaml'].some(function (ext) { return str.toLocaleLowerCase().endsWith("." + ext); });
178 return isNotEmpty && hasCorrectExtension;
179 }
180 },
181 {
182 type: 'input',
183 name: 'script',
184 message: 'What script in package.json should run the codegen?',
185 validate: function (str) { return str.length > 0; }
186 }
187 ])];
188 case 1:
189 answers = _b.sent();
190 config = {
191 overwrite: true,
192 schema: answers.schema,
193 documents: answers.target === Tags.client ? answers.documents : null,
194 generates: (_a = {},
195 _a[answers.output] = {
196 plugins: answers.plugins.map(function (p) { return p.value; })
197 },
198 _a)
199 };
200 // introspection
201 if (answers.introspection) {
202 addIntrospection(config);
203 }
204 relativePath = writeConfig(answers, config).relativePath;
205 // write package.json
206 writePackage(answers, relativePath);
207 // Emit status to the terminal
208 log("\n Config file generated at " + chalk_1.default.bold(relativePath) + "\n \n " + chalk_1.default.bold('$ npm install') + "\n\n To install the plugins.\n\n " + chalk_1.default.bold("$ npm run " + answers.script) + "\n\n To run GraphQL Code Generator.\n ");
209 return [2 /*return*/];
210 }
211 });
212 });
213}
214exports.init = init;
215// adds an introspection to `generates`
216function addIntrospection(config) {
217 config.generates['./graphql.schema.json'] = {
218 plugins: ['introspection']
219 };
220}
221// Parses config and writes it to a file
222function writeConfig(answers, config) {
223 var ext = answers.config.toLocaleLowerCase().endsWith('.json') ? 'json' : 'yml';
224 var content = ext === 'json' ? JSON.stringify(config) : YAML.stringify(config);
225 var fullPath = path_1.resolve(process.cwd(), answers.config);
226 var relativePath = path_1.relative(process.cwd(), answers.config);
227 fs_1.writeFileSync(fullPath, content, {
228 encoding: 'utf-8'
229 });
230 return {
231 relativePath: relativePath,
232 fullPath: fullPath
233 };
234}
235// Updates package.json (script and plugins as dependencies)
236function writePackage(answers, configLocation) {
237 // script
238 var pkgPath = path_1.resolve(process.cwd(), 'package.json');
239 var pkgContent = fs_1.readFileSync(pkgPath, {
240 encoding: 'utf-8'
241 });
242 var pkg = JSON.parse(pkgContent);
243 var indent = detectIndent(pkgContent).indent;
244 if (!pkg.scripts) {
245 pkg.scripts = {};
246 }
247 pkg.scripts[answers.script] = "gql-gen --config " + configLocation;
248 // plugin
249 if (!pkg.devDependencies) {
250 pkg.devDependencies = {};
251 }
252 // read codegen's version
253 var version = JSON.parse(fs_1.readFileSync(path_1.resolve(__dirname, '../package.json'), {
254 encoding: 'utf-8'
255 })).version;
256 answers.plugins.forEach(function (plugin) {
257 pkg.devDependencies[plugin.package] = version;
258 });
259 fs_1.writeFileSync(pkgPath, JSON.stringify(pkg, null, indent));
260}
261//# sourceMappingURL=init.js.map
\No newline at end of file