UNPKG

9.17 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13Object.defineProperty(exports, "__esModule", { value: true });
14var commander_1 = require("commander");
15var fs_1 = require("fs");
16var path_1 = require("path");
17var cli_error_1 = require("./utils/cli-error");
18var YAML = require("json-to-pretty-yaml");
19var is_browser_1 = require("./utils/is-browser");
20function collect(val, memo) {
21 memo.push(val);
22 return memo;
23}
24exports.initCLI = function (args) {
25 var command = new commander_1.Command()
26 .usage('gql-gen [options]')
27 .option('-s, --schema <path>', 'Path to GraphQL schema: local JSON file, GraphQL endpoint, local file that exports GraphQLSchema/AST/JSON')
28 .option('-cs, --clientSchema <path>', 'Path to GraphQL client schema: local JSON file, local file that exports GraphQLSchema/AST/JSON')
29 .option('-h, --header [header]', 'Header to add to the introspection HTTP request when using --url/--schema with url', collect, [])
30 .option('-t, --template <template-name>', 'Language/platform name templates, or a name of NPM modules that `export default` GqlGenConfig object')
31 .option('-p, --project <project-path>', 'Project path(s) to scan for custom template files')
32 .option('--config <json-file>', 'Codegen configuration file, defaults to: ./gql-gen.json')
33 .option('-m, --skip-schema', 'Generates only client side documents, without server side schema types')
34 .option('-c, --skip-documents', 'Generates only server side schema types, without client side documents')
35 .option('-o, --out <path>', 'Output file(s) path', String, './')
36 .option('-r, --require [require]', 'module to preload (option can be repeated)', collect, [])
37 .option('-ow, --no-overwrite', 'Skip file writing if the output file(s) already exists in path')
38 .option('-w, --watch', 'Watch for changes and execute generation automatically')
39 .option('--silent', 'Does not print anything to the console')
40 .option('-ms, --merge-schema <merge-logic>', 'Merge schemas with custom logic')
41 .arguments('<options> [documents...]')
42 .parse(args);
43 return command;
44};
45exports.validateCliOptions = function (options) {
46 var schema = options.schema;
47 var template = options.template;
48 var project = options.project;
49 if (!schema && is_browser_1.isNode) {
50 var _a = require('graphql-config'), getGraphQLProjectConfig = _a.getGraphQLProjectConfig, ConfigNotFoundError = _a.ConfigNotFoundError;
51 try {
52 var graphqlProjectConfig = getGraphQLProjectConfig(project);
53 options.schema = graphqlProjectConfig.schemaPath;
54 }
55 catch (e) {
56 if (e instanceof ConfigNotFoundError) {
57 cli_error_1.cliError('Flag --schema is missing!');
58 }
59 }
60 }
61 if (!template && !project) {
62 cli_error_1.cliError('Please specify language/platform, using --template flag!');
63 }
64};
65function transformTemplatesToPlugins(options, templateSpecificConfig) {
66 if (templateSpecificConfig === void 0) { templateSpecificConfig = {}; }
67 if (options.template === 'ts' ||
68 options.template === 'typescript' ||
69 options.template === 'graphql-codegen-typescript-template') {
70 return {
71 config: templateSpecificConfig,
72 plugins: [
73 templateSpecificConfig.printTime ? 'time' : null,
74 'typescript-common',
75 options.skipDocuments ? null : 'typescript-client',
76 options.skipSchema ? null : 'typescript-server'
77 ].filter(function (s) { return s; })
78 };
79 }
80 else if (options.template === 'typescript-resolvers' ||
81 options.template === 'graphql-codegen-typescript-resolvers-template') {
82 return {
83 config: templateSpecificConfig,
84 plugins: [templateSpecificConfig.printTime ? 'time' : null, 'typescript-common', 'typescript-resolvers'].filter(function (s) { return s; })
85 };
86 }
87 else if (options.template === 'typescript-mongodb' ||
88 options.template === 'graphql-codegen-typescript-mongodb-template') {
89 return {
90 config: templateSpecificConfig,
91 plugins: [
92 templateSpecificConfig.printTime ? 'time' : null,
93 'typescript-common',
94 'typescript-server',
95 'typescript-mongodb'
96 ].filter(function (s) { return s; })
97 };
98 }
99 else if (options.template === 'apollo-angular' || options.template === 'graphql-codegen-apollo-angular-template') {
100 return {
101 config: templateSpecificConfig,
102 plugins: [
103 templateSpecificConfig.printTime ? 'time' : null,
104 'typescript-common',
105 'typescript-client',
106 'typescript-apollo-angular'
107 ].filter(function (s) { return s; })
108 };
109 }
110 else if (options.template === 'react-apollo' ||
111 options.template === 'graphql-codegen-typescript-react-apollo-template') {
112 return {
113 config: templateSpecificConfig,
114 plugins: [
115 templateSpecificConfig.printTime ? 'time' : null,
116 'typescript-common',
117 'typescript-client',
118 'typescript-react-apollo'
119 ].filter(function (s) { return s; })
120 };
121 }
122 else if (options.template === 'introspection' || options.template === 'graphql-codegen-introspection-template') {
123 return {
124 config: templateSpecificConfig,
125 plugins: ['introspection'].filter(function (s) { return s; })
126 };
127 }
128 else if (options.template === 'graphql-files-typescript' ||
129 options.template === 'graphql-codegen-graphql-files-typescript-modules') {
130 return {
131 config: templateSpecificConfig,
132 plugins: ['typescript-graphql-files-modules'].filter(function (s) { return s; })
133 };
134 }
135 return { plugins: [options.template].filter(function (a) { return a; }) };
136}
137function getConfigFromEnvVars() {
138 return Object.keys(process.env)
139 .filter(function (name) { return name.startsWith('CODEGEN_'); })
140 .reduce(function (prev, name) {
141 var cleanName = name
142 .replace('CODEGEN_', '')
143 .toLowerCase()
144 .replace(/[-_]+/g, ' ')
145 .replace(/[^\w\s]/g, '')
146 .replace(/ (.)/g, function (res) { return res.toUpperCase(); })
147 .replace(/ /g, '');
148 var value = process.env[name];
149 if (value === 'true') {
150 value = true;
151 }
152 else if (value === 'false') {
153 value = false;
154 }
155 prev[cleanName] = value;
156 return prev;
157 }, {});
158}
159function createConfigFromOldCli(options) {
160 var _a, _b;
161 exports.validateCliOptions(options);
162 var rootConfig = {};
163 var configPath = options.config ? options.config : fs_1.existsSync(path_1.join(process.cwd(), './gql-gen.json'));
164 if (configPath && typeof configPath === 'string') {
165 var rawObj = JSON.parse(fs_1.readFileSync(configPath, 'utf-8'));
166 rootConfig = (rawObj || {}).generatorConfig || {};
167 }
168 var envVarsConfig = getConfigFromEnvVars();
169 rootConfig = __assign({}, rootConfig, envVarsConfig);
170 var schema = options.schema;
171 if (options.header && Array.isArray(options.header) && options.header.length > 0) {
172 schema = (_a = {},
173 _a[options.schema] = {
174 headers: options.header.reduce(function (prev, h) {
175 var _a;
176 var splitted = h.split(':').map(function (p) { return p.trim(); });
177 var name = splitted[0];
178 var value = splitted[1];
179 return __assign({}, prev, (_a = {}, _a[name] = value, _a));
180 }, {})
181 },
182 _a);
183 }
184 var configObject = {
185 schema: [schema, options.clientSchema].filter(function (s) { return s; }),
186 documents: options.args || [],
187 config: rootConfig,
188 generates: (_b = {},
189 _b[options.out] = transformTemplatesToPlugins(options, __assign({}, rootConfig, (options.templateConfig || {}))),
190 _b),
191 silent: options.silent,
192 watch: options.watch,
193 require: options.require
194 };
195 console['warn']("\n Note: You are using the old API of graphql-code-generator. You can easily migrate by creating \"codegen.yml\" file in your project with the following content:\n \n" + YAML.stringify(configObject) + "\n\n Then, make sure that your script is executing just \"gql-gen\" (without any cli flags).\n ");
196 return configObject;
197}
198exports.createConfigFromOldCli = createConfigFromOldCli;
199//# sourceMappingURL=old-cli-config.js.map
\No newline at end of file