-
Notifications
You must be signed in to change notification settings - Fork 463
Expand file tree
/
Copy pathgenerate.ts
More file actions
241 lines (218 loc) · 7.83 KB
/
generate.ts
File metadata and controls
241 lines (218 loc) · 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import "apollo-codegen-core/lib/polyfills";
import { Command, flags } from "@oclif/command";
import * as Listr from "listr";
import * as path from "path";
import { TargetType, default as generate } from "../../generate";
import { buildClientSchema } from "graphql";
import * as fg from "glob";
import { fs, withGlobalFS } from "apollo-codegen-core/lib/localfs";
import { promisify } from "util";
import { loadSchemaStep } from "../../load-schema";
import { engineFlags } from "../../engine-cli";
export default class Generate extends Command {
static description =
"Generate static types for GraphQL queries. Can use the published schema in Apollo Engine or a downloaded schema.";
static flags = {
help: flags.help({
char: "h",
description: "Show command help"
}),
queries: flags.string({
description:
"Path to your GraphQL queries, can include search tokens like **",
default: "**/*.graphql"
}),
schema: flags.string({
description: "Path to your GraphQL schema introspection result"
}),
...engineFlags,
target: flags.string({
description:
"Type of code generator to use (swift | typescript | flow | scala), inferred from output"
}),
namespace: flags.string({
description: "The namespace to emit generated code into."
}),
passthroughCustomScalars: flags.boolean({
description: "Use your own types for custom scalars"
}),
customScalarsPrefix: flags.string({
description:
"Include a prefix when using provided types for custom scalars"
}),
addTypename: flags.boolean({
description: "Automatically add __typename to your queries"
}),
operationIdsPath: flags.string({
description:
"Path to an operation id JSON map file. If specified, also stores the operation ids (hashes) as properties on operation types [currently Swift-only]"
}),
mergeInFieldsFromFragmentSpreads: flags.boolean({
description: "Merge fragment fields onto its enclosing type"
}),
useFlowExactObjects: flags.boolean({
description: "Use Flow exact objects for generated types [flow only]"
}),
useFlowReadOnlyTypes: flags.boolean({
description: "Use Flow read only types for generated types [flow only]"
}),
only: flags.string({
description:
"Parse all input files, but only output generated code for the specified file [Swift only]"
}),
tagName: flags.string({
description:
"Name of the template literal tag used to identify template literals containing GraphQL queries in Javascript/Typescript code",
default: "gql"
}),
outputFlat: flags.boolean({
description:
'By default, TypeScript/Flow will put each generated file in a directory next to its source file using the value of the "output" as the directory name. Set "outputFlat" to put all generated files in the directory relative to the current working directory defined by "output".'
})
};
static args = [
{
name: "output",
description: `Directory to which generated files will be written.
- For TypeScript/Flow generators, this specifies a directory relative to each source file by default.
- For TypeScript/Flow generators with the "outputFlat" flag is set, and for the Swift generator, this specifies a file or directory (absolute or relative to the current working directory) to which:
- a file will be written for each query (if "output" is a directory)
- all generated types will be written
- For all other types, this defines a file (absolute or relative to the current working directory) to which all generated types are written.`
}
];
async run() {
const { flags, args } = this.parse(Generate);
let inferredTarget: TargetType = "" as TargetType;
if (flags.target) {
if (
[
"json",
"swift",
"typescript",
"flow",
"scala",
"typescript-legacy",
"flow-legacy"
].includes(flags.target)
) {
inferredTarget = flags.target as TargetType;
} else {
this.error(`Unsupported target: ${flags.target}`);
}
} else if (args.output) {
switch (args.output.split(".").reverse()[0]) {
case "json":
inferredTarget = "json";
break;
case "swift":
inferredTarget = "swift";
break;
case "ts" || "tsx":
inferredTarget = "typescript";
break;
case "js" || "jsx":
inferredTarget = "flow";
break;
case "scala":
inferredTarget = "scala";
break;
default:
this.error(
"Could not infer target from output file type, please use --target"
);
return;
}
}
if (
!args.output &&
inferredTarget != "typescript" &&
inferredTarget != "flow"
) {
this.error(
"The output path must be specified in the arguments for Swift and Scala"
);
return;
}
if (
!flags.outputFlat &&
(inferredTarget === "typescript" || inferredTarget === "flow") &&
(args.output && (path.isAbsolute(args.output) || args.output.split(path.sep).length > 1))
) {
this.error(
"For TypeScript and Flow generators, \"output\" must be empty or a single directory name, unless the \"outputFlat\" flag is set."
);
return;
}
const apiKey = flags.key;
const pullFromEngine = !!apiKey && !flags.schema;
const tasks: Listr = new Listr([
{
title: "Scanning for GraphQL queries",
task: async (ctx, task) => {
const paths = withGlobalFS(() => {
return (flags.queries ? flags.queries.split("\n") : []).flatMap(p =>
fg.sync(p)
);
});
task.title = `Scanning for GraphQL queries (${paths.length} found)`;
ctx.queryPaths = paths;
}
},
loadSchemaStep(
this,
pullFromEngine,
apiKey,
flags.engine,
"Loading GraphQL schema",
async ctx => {
const schemaFileContent = await promisify(fs.readFile)(
path.resolve(flags.schema as string)
);
const schemaData = JSON.parse((schemaFileContent as any) as string);
ctx.schema = schemaData.data
? schemaData.data.__schema
: schemaData.__schema
? schemaData.__schema
: schemaData;
}
),
{
title: "Parsing GraphQL schema",
task: async ctx => {
ctx.schema = buildClientSchema({ __schema: ctx.schema });
}
},
{
title: "Generating query files",
task: async (ctx, task) => {
task.title = `Generating query files with '${inferredTarget}' target`;
const writtenFiles = generate(
ctx.queryPaths,
ctx.schema,
typeof args.output === "string" ? args.output : "__generated__",
flags.only,
inferredTarget,
flags.tagName as string,
!flags.outputFlat,
{
passthroughCustomScalars:
flags.passthroughCustomScalars || !!flags.customScalarsPrefix,
customScalarsPrefix: flags.customScalarsPrefix || "",
addTypename: flags.addTypename,
namespace: flags.namespace,
operationIdsPath: flags.operationIdsPath,
generateOperationIds: !!flags.operationIdsPath,
mergeInFieldsFromFragmentSpreads:
flags.mergeInFieldsFromFragmentSpreads,
useFlowExactObjects: flags.useFlowExactObjects,
useFlowReadOnlyTypes: flags.useFlowReadOnlyTypes
}
);
task.title = `Generating query files with '${inferredTarget}' target - wrote ${writtenFiles} files`;
}
}
]);
return tasks.run();
}
}