1 | import inquirer from 'inquirer';
|
2 | import chalk from 'chalk';
|
3 | import { resolve, relative } from 'path';
|
4 | import { writeFileSync, readFileSync } from 'fs';
|
5 | import YAML from 'json-to-pretty-yaml';
|
6 | import detectIndent from 'detect-indent';
|
7 | var Tags;
|
8 | (function (Tags) {
|
9 | Tags["client"] = "Client";
|
10 | Tags["server"] = "Server";
|
11 | Tags["typescript"] = "TypeScript";
|
12 | Tags["angular"] = "Angular";
|
13 | Tags["react"] = "React";
|
14 | })(Tags || (Tags = {}));
|
15 | function log(...msgs) {
|
16 |
|
17 | console.log(...msgs);
|
18 | }
|
19 | const plugins = [
|
20 | {
|
21 | name: `TypeScript Common ${chalk.italic('(required by client and server plugins)')}`,
|
22 | package: 'graphql-codegen-typescript-common',
|
23 | value: 'typescript-common',
|
24 | available: () => true
|
25 | },
|
26 | {
|
27 | name: `TypeScript Client ${chalk.italic('(operations and fragments)')}`,
|
28 | package: 'graphql-codegen-typescript-client',
|
29 | value: 'typescript-client',
|
30 | available: tags => tags.some(tag => [Tags.client].includes(tag))
|
31 | },
|
32 | {
|
33 | name: `TypeScript Server ${chalk.italic('(GraphQL Schema)')}`,
|
34 | package: 'graphql-codegen-typescript-server',
|
35 | value: 'typescript-server',
|
36 | available: tags => tags.some(tag => [Tags.client, Tags.server].includes(tag))
|
37 | },
|
38 | {
|
39 | name: `TypeScript Resolvers ${chalk.italic('(strongly typed resolve functions)')}`,
|
40 | package: 'graphql-codegen-typescript-resolvers',
|
41 | value: 'typescript-resolvers',
|
42 | available: tags => tags.some(tag => [Tags.server].includes(tag))
|
43 | },
|
44 | {
|
45 | name: `TypeScript Apollo Angular ${chalk.italic('(GQL services)')}`,
|
46 | package: 'graphql-codegen-typescript-apollo-angular',
|
47 | value: 'typescript-apollo-angular',
|
48 | available: tags => {
|
49 | const hasAngular = tags.includes(Tags.angular);
|
50 | const noReact = !tags.includes(Tags.react);
|
51 | return hasAngular && noReact;
|
52 | }
|
53 | },
|
54 | {
|
55 | name: `TypeScript React Apollo ${chalk.italic('(typed components and HOCs)')}`,
|
56 | package: 'graphql-codegen-typescript-react-apollo',
|
57 | value: 'typescript-react-apollo',
|
58 | available: tags => {
|
59 | const hasReact = tags.includes(Tags.react);
|
60 | const noAngular = !tags.includes(Tags.angular);
|
61 | return hasReact && noAngular;
|
62 | }
|
63 | },
|
64 | {
|
65 | name: `TypeScript MongoDB ${chalk.italic('(typed MongoDB objects)')}`,
|
66 | package: 'graphql-codegen-typescript-mongodb',
|
67 | value: 'typescript-mongodb',
|
68 | available: tags => tags.includes(Tags.server)
|
69 | },
|
70 | {
|
71 | name: `TypeScript GraphQL files modules ${chalk.italic('(declarations for .graphql files)')}`,
|
72 | package: 'graphql-codegen-typescript-graphql-files-modules',
|
73 | value: 'typescript-graphql-files-modules',
|
74 | available: tags => tags.includes(Tags.client)
|
75 | },
|
76 | {
|
77 | name: `Introspection Fragment Matcher ${chalk.italic('(for Apollo Client)')}`,
|
78 | package: 'graphql-codegen-fragment-matcher',
|
79 | value: 'fragment-matcher',
|
80 | available: tags => tags.includes(Tags.client)
|
81 | }
|
82 | ];
|
83 | export async function init() {
|
84 | log(`
|
85 | Welcome to ${chalk.bold('GraphQL Code Generator')}!
|
86 | Answer few questions and we will setup everything for you.
|
87 | `);
|
88 | const possibleTargets = await guessTargets();
|
89 | function normalizeTargets(targets) {
|
90 | return [].concat(...targets);
|
91 | }
|
92 | const answers = await inquirer.prompt([
|
93 | {
|
94 | type: 'checkbox',
|
95 | name: 'targets',
|
96 | message: `What type of application are you building?`,
|
97 | choices: [
|
98 | {
|
99 | name: 'Backend - API or server',
|
100 | key: 'backend',
|
101 | value: [Tags.server],
|
102 | checked: possibleTargets.Server
|
103 | },
|
104 | {
|
105 | name: 'Application built with Angular',
|
106 | key: 'angular',
|
107 | value: [Tags.angular, Tags.client],
|
108 | checked: possibleTargets.Angular
|
109 | },
|
110 | {
|
111 | name: 'Application built with React',
|
112 | key: 'react',
|
113 | value: [Tags.react, Tags.client],
|
114 | checked: possibleTargets.React
|
115 | },
|
116 | {
|
117 | name: 'Application built with other framework or vanilla JS',
|
118 | key: 'client',
|
119 | value: [Tags.client],
|
120 | checked: false
|
121 | }
|
122 | ]
|
123 | },
|
124 | {
|
125 | type: 'input',
|
126 | name: 'schema',
|
127 | message: 'Where is your schema?:',
|
128 | suffix: chalk.grey(' (path or url)'),
|
129 | default: 'https://localhost:4000',
|
130 | validate: (str) => str.length > 0
|
131 | },
|
132 | {
|
133 | type: 'input',
|
134 | name: 'documents',
|
135 | message: 'Where are your operations and fragments?:',
|
136 | when: answers => {
|
137 |
|
138 |
|
139 | answers.targets = normalizeTargets(answers.targets);
|
140 | return answers.targets.includes(Tags.client);
|
141 | },
|
142 | default: '**/*.graphql',
|
143 | validate: (str) => str.length > 0
|
144 | },
|
145 | {
|
146 | type: 'checkbox',
|
147 | name: 'plugins',
|
148 | message: 'Pick plugins:',
|
149 | choices: answers => {
|
150 | return plugins
|
151 | .filter(p => p.available(answers.targets))
|
152 | .map(p => {
|
153 | return {
|
154 | name: p.name,
|
155 | value: p,
|
156 | checked: p.value === 'typescript-common'
|
157 | };
|
158 | });
|
159 | },
|
160 | validate: (plugins) => plugins.length > 0
|
161 | },
|
162 | {
|
163 | type: 'input',
|
164 | name: 'output',
|
165 | message: 'Where to write the output:',
|
166 | default: 'src/generated/graphql.ts',
|
167 | validate: (str) => str.length > 0
|
168 | },
|
169 | {
|
170 | type: 'confirm',
|
171 | name: 'introspection',
|
172 | message: 'Do you want to generate an introspection file?'
|
173 | },
|
174 | {
|
175 | type: 'input',
|
176 | name: 'config',
|
177 | message: 'How to name the config file?',
|
178 | default: 'codegen.yml',
|
179 | validate: (str) => {
|
180 | const isNotEmpty = str.length > 0;
|
181 | const hasCorrectExtension = ['json', 'yml', 'yaml'].some(ext => str.toLocaleLowerCase().endsWith(`.${ext}`));
|
182 | return isNotEmpty && hasCorrectExtension;
|
183 | }
|
184 | },
|
185 | {
|
186 | type: 'input',
|
187 | name: 'script',
|
188 | message: 'What script in package.json should run the codegen?',
|
189 | validate: (str) => str.length > 0
|
190 | }
|
191 | ]);
|
192 |
|
193 | const config = {
|
194 | overwrite: true,
|
195 | schema: answers.schema,
|
196 | documents: answers.targets.includes(Tags.client) ? answers.documents : null,
|
197 | generates: {
|
198 | [answers.output]: {
|
199 | plugins: answers.plugins.map(p => p.value)
|
200 | }
|
201 | }
|
202 | };
|
203 |
|
204 | if (answers.introspection) {
|
205 | addIntrospection(config);
|
206 | }
|
207 |
|
208 | const { relativePath } = writeConfig(answers, config);
|
209 |
|
210 | writePackage(answers, relativePath);
|
211 |
|
212 | log(`
|
213 | Config file generated at ${chalk.bold(relativePath)}
|
214 |
|
215 | ${chalk.bold('$ npm install')}
|
216 |
|
217 | To install the plugins.
|
218 |
|
219 | ${chalk.bold(`$ npm run ${answers.script}`)}
|
220 |
|
221 | To run GraphQL Code Generator.
|
222 | `);
|
223 | }
|
224 |
|
225 | function addIntrospection(config) {
|
226 | config.generates['./graphql.schema.json'] = {
|
227 | plugins: ['introspection']
|
228 | };
|
229 | }
|
230 |
|
231 | function writeConfig(answers, config) {
|
232 | const ext = answers.config.toLocaleLowerCase().endsWith('.json') ? 'json' : 'yml';
|
233 | const content = ext === 'json' ? JSON.stringify(config) : YAML.stringify(config);
|
234 | const fullPath = resolve(process.cwd(), answers.config);
|
235 | const relativePath = relative(process.cwd(), answers.config);
|
236 | writeFileSync(fullPath, content, {
|
237 | encoding: 'utf-8'
|
238 | });
|
239 | return {
|
240 | relativePath,
|
241 | fullPath
|
242 | };
|
243 | }
|
244 |
|
245 | function writePackage(answers, configLocation) {
|
246 |
|
247 | const pkgPath = resolve(process.cwd(), 'package.json');
|
248 | const pkgContent = readFileSync(pkgPath, {
|
249 | encoding: 'utf-8'
|
250 | });
|
251 | const pkg = JSON.parse(pkgContent);
|
252 | const { indent } = detectIndent(pkgContent);
|
253 | if (!pkg.scripts) {
|
254 | pkg.scripts = {};
|
255 | }
|
256 | pkg.scripts[answers.script] = `gql-gen --config ${configLocation}`;
|
257 |
|
258 | if (!pkg.devDependencies) {
|
259 | pkg.devDependencies = {};
|
260 | }
|
261 |
|
262 | const { version } = JSON.parse(readFileSync(resolve(__dirname, '../package.json'), {
|
263 | encoding: 'utf-8'
|
264 | }));
|
265 | answers.plugins.forEach(plugin => {
|
266 | pkg.devDependencies[plugin.package] = version;
|
267 | });
|
268 | writeFileSync(pkgPath, JSON.stringify(pkg, null, indent));
|
269 | }
|
270 | async function guessTargets() {
|
271 | const pkg = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), {
|
272 | encoding: 'utf-8'
|
273 | }));
|
274 | const dependencies = Object.keys(Object.assign({}, pkg.dependencies, pkg.devDependencies));
|
275 | return {
|
276 | [Tags.angular]: isAngular(dependencies),
|
277 | [Tags.react]: isReact(dependencies),
|
278 | [Tags.client]: false,
|
279 | [Tags.server]: false,
|
280 | [Tags.typescript]: isTypescript(dependencies)
|
281 | };
|
282 | }
|
283 | function isAngular(dependencies) {
|
284 | return dependencies.includes('@angular/core');
|
285 | }
|
286 | function isReact(dependencies) {
|
287 | return dependencies.includes('react');
|
288 | }
|
289 | function isTypescript(dependencies) {
|
290 | return dependencies.includes('typescript');
|
291 | }
|
292 |
|
\ | No newline at end of file |