Skip to content

Commit 09d0831

Browse files
authored
Improve typing of options and add more codegen tests (#465)
* Improve typing of options and test generating operation IDs * Add unit tests for --only flag in Swift * Fix compile error * Fix unit tests * Update package-locks and fix unit tests
1 parent 19522f3 commit 09d0831

9 files changed

Lines changed: 5422 additions & 16905 deletions

File tree

package-lock.json

Lines changed: 846 additions & 7115 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/apollo-cli/package-lock.json

Lines changed: 4378 additions & 9779 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/apollo-cli/src/commands/codegen/__tests__/__snapshots__/generate.test.ts.snap

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,70 @@
11
// Jest Snapshot v1, https://goo.gl/fbAQLP
22

3+
exports[`successful codegen generates operation IDs files when flag is set 1`] = `
4+
"{
5+
\\"4de1e386589b0853a102a87a3f21ca25266116517e59c1e8be9442e2571f00bc\\": {
6+
\\"name\\": \\"SimpleQuery\\",
7+
\\"source\\": \\"query SimpleQuery {\\\\n hello\\\\n}\\"
8+
}
9+
}"
10+
`;
11+
12+
exports[`successful codegen handles only flag for Swift target 1`] = `
13+
Array [
14+
Array [
15+
"../../../../outDirectory/__create_this_directory",
16+
"",
17+
],
18+
Array [
19+
"../../../../outDirectory/Types.graphql.swift",
20+
"// This file was automatically generated and should not be edited.
21+
22+
import Apollo",
23+
],
24+
Array [
25+
"../../../../outDirectory/queryTwo.graphql.swift",
26+
"// This file was automatically generated and should not be edited.
27+
28+
import Apollo
29+
30+
public final class OtherQueryQuery: GraphQLQuery {
31+
public let operationDefinition =
32+
\\"query OtherQuery {\\\\n hello\\\\n}\\"
33+
34+
public init() {
35+
}
36+
37+
public struct Data: GraphQLSelectionSet {
38+
public static let possibleTypes = [\\"Query\\"]
39+
40+
public static let selections: [GraphQLSelection] = [
41+
GraphQLField(\\"hello\\", type: .nonNull(.scalar(String.self))),
42+
]
43+
44+
public private(set) var resultMap: ResultMap
45+
46+
public init(unsafeResultMap: ResultMap) {
47+
self.resultMap = unsafeResultMap
48+
}
49+
50+
public init(hello: String) {
51+
self.init(unsafeResultMap: [\\"__typename\\": \\"Query\\", \\"hello\\": hello])
52+
}
53+
54+
public var hello: String {
55+
get {
56+
return resultMap[\\"hello\\"]! as! String
57+
}
58+
set {
59+
resultMap.updateValue(newValue, forKey: \\"hello\\")
60+
}
61+
}
62+
}
63+
}",
64+
],
65+
]
66+
`;
67+
368
exports[`successful codegen infers Flow target and writes types 1`] = `
469
"
570
@@ -309,3 +374,59 @@ export interface SimpleQuery {
309374
// END Enums and Input Objects
310375
//=============================================================="
311376
`;
377+
378+
exports[`successful codegen writes exact Flow types when the flag is set 1`] = `
379+
"
380+
381+
/* @flow */
382+
/* eslint-disable */
383+
// This file was automatically generated and should not be edited.
384+
385+
// ====================================================
386+
// GraphQL query operation: SimpleQuery
387+
// ====================================================
388+
389+
export type SimpleQuery = {|
390+
hello: string
391+
|};
392+
393+
/* @flow */
394+
/* eslint-disable */
395+
// This file was automatically generated and should not be edited.
396+
397+
//==============================================================
398+
// START Enums and Input Objects
399+
//==============================================================
400+
401+
//==============================================================
402+
// END Enums and Input Objects
403+
//=============================================================="
404+
`;
405+
406+
exports[`successful codegen writes read-only Flow types when the flag is set 1`] = `
407+
"
408+
409+
/* @flow */
410+
/* eslint-disable */
411+
// This file was automatically generated and should not be edited.
412+
413+
// ====================================================
414+
// GraphQL query operation: SimpleQuery
415+
// ====================================================
416+
417+
export type SimpleQuery = {
418+
+hello: string
419+
};
420+
421+
/* @flow */
422+
/* eslint-disable */
423+
// This file was automatically generated and should not be edited.
424+
425+
//==============================================================
426+
// START Enums and Input Objects
427+
//==============================================================
428+
429+
//==============================================================
430+
// END Enums and Input Objects
431+
//=============================================================="
432+
`;
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
query OtherQuery {
2+
hello
3+
}

packages/apollo-cli/src/commands/codegen/__tests__/generate.test.ts

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ const simpleQuery = fs.readFileSync(
2828
path.resolve(__dirname, "./fixtures/simpleQuery.graphql")
2929
);
3030

31+
const otherQuery = fs.readFileSync(
32+
path.resolve(__dirname, "./fixtures/otherQuery.graphql")
33+
);
34+
3135
beforeEach(() => {
3236
vol.reset();
3337
vol.fromJSON({
@@ -50,6 +54,32 @@ describe("successful codegen", () => {
5054
expect(mockFS.readFileSync("API.swift").toString()).toMatchSnapshot();
5155
});
5256

57+
test
58+
.do(() => {
59+
vol.fromJSON({
60+
"schema.json": JSON.stringify(fullSchema.__schema),
61+
"queryOne.graphql": simpleQuery.toString()
62+
});
63+
})
64+
.command(["codegen:generate", "--schema=schema.json", "--operationIdsPath=myOperationIDs.json", "API.swift"])
65+
.it("generates operation IDs files when flag is set", () => {
66+
expect(mockFS.readFileSync("myOperationIDs.json").toString()).toMatchSnapshot();
67+
});
68+
69+
test
70+
.do(() => {
71+
vol.fromJSON({
72+
"schema.json": JSON.stringify(fullSchema.__schema),
73+
"queryOne.graphql": simpleQuery.toString(),
74+
"queryTwo.graphql": otherQuery.toString(),
75+
"outDirectory/__create_this_directory": ""
76+
});
77+
})
78+
.command(["codegen:generate", "--schema=schema.json", "--only=queryTwo.graphql", "--target=swift", "outDirectory"])
79+
.it("handles only flag for Swift target", () => {
80+
expect(Object.entries(vol.toJSON("outDirectory")).map(arr => [path.relative(__dirname, arr[0]), arr[1]])).toMatchSnapshot();
81+
});
82+
5383
test
5484
.do(() => {
5585
vol.fromJSON({
@@ -86,6 +116,30 @@ describe("successful codegen", () => {
86116
expect(mockFS.readFileSync("API.js").toString()).toMatchSnapshot();
87117
});
88118

119+
test
120+
.do(() => {
121+
vol.fromJSON({
122+
"schema.json": JSON.stringify(fullSchema.__schema),
123+
"queryOne.graphql": simpleQuery.toString()
124+
});
125+
})
126+
.command(["codegen:generate", "--schema=schema.json", "--useFlowExactObjects", "--outputFlat", "API.js"])
127+
.it("writes exact Flow types when the flag is set", () => {
128+
expect(mockFS.readFileSync("API.js").toString()).toMatchSnapshot();
129+
});
130+
131+
test
132+
.do(() => {
133+
vol.fromJSON({
134+
"schema.json": JSON.stringify(fullSchema.__schema),
135+
"queryOne.graphql": simpleQuery.toString()
136+
});
137+
})
138+
.command(["codegen:generate", "--schema=schema.json", "--useFlowReadOnlyTypes", "--outputFlat", "API.js"])
139+
.it("writes read-only Flow types when the flag is set", () => {
140+
expect(mockFS.readFileSync("API.js").toString()).toMatchSnapshot();
141+
});
142+
89143
test
90144
.do(() => {
91145
vol.fromJSON({
@@ -287,4 +341,9 @@ describe("error handling", () => {
287341
expect(err.message).toMatch(/The output path must be specified/)
288342
)
289343
.it("errors when no output file is provided");
344+
345+
test
346+
.command(["codegen:generate", "output-file"])
347+
.catch(err => expect(err.message).toMatch(/Could not infer target from output file type, please use --target/))
348+
.it("errors when target cannot be inferred");
290349
});

packages/apollo-cli/src/commands/codegen/generate.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export default class Generate extends Command {
6060
description: "Merge fragment fields onto its enclosing type"
6161
}),
6262
useFlowExactObjects: flags.boolean({
63-
description: "Use Flow read only types for generated types [flow only]"
63+
description: "Use Flow exact objects for generated types [flow only]"
6464
}),
6565
useFlowReadOnlyTypes: flags.boolean({
6666
description: "Use Flow read only types for generated types [flow only]"
@@ -212,13 +212,13 @@ export default class Generate extends Command {
212212
ctx.queryPaths,
213213
ctx.schema,
214214
typeof args.output === "string" ? args.output : "__generated__",
215-
flags.only ? path.resolve(flags.only) : "",
215+
flags.only,
216216
inferredTarget,
217217
flags.tagName as string,
218218
!flags.outputFlat,
219219
{
220220
passthroughCustomScalars:
221-
flags.passthroughCustomScalars || flags.customScalarsPrefix,
221+
flags.passthroughCustomScalars || !!flags.customScalarsPrefix,
222222
customScalarsPrefix: flags.customScalarsPrefix || "",
223223
addTypename: flags.addTypename,
224224
namespace: flags.namespace,

packages/apollo-cli/src/commands/queries/__tests__/check.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ describe("successful checks", () => {
136136
.nock(ENGINE_URI, engineSuccess())
137137
.env({ ENGINE_API_KEY })
138138
.stdout()
139-
.command(["queries:check", "--queries=./client/**"])
139+
.command(["queries:check", "--queries=./client/*.graphql"])
140140
.exit(1)
141141
.it("compares against a schema from a custom directory", () => {
142142
expect(stdout).toContain("FAILURE");

packages/apollo-cli/src/generate.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import * as path from "path";
33

44
import { loadAndMergeQueryDocuments } from "apollo-codegen-core/lib/loading";
55
import { validateQueryDocument } from "./validation";
6-
import { compileToIR } from "apollo-codegen-core/lib/compiler";
7-
import { compileToLegacyIR } from "apollo-codegen-core/lib/compiler/legacyIR";
6+
import { compileToIR, CompilerContext, CompilerOptions } from "apollo-codegen-core/lib/compiler";
7+
import { compileToLegacyIR, CompilerOptions as LegacyCompilerOptions } from "apollo-codegen-core/lib/compiler/legacyIR";
88
import serializeToJSON from "apollo-codegen-core/lib/serializeToJSON";
99
import { BasicGeneratedFile } from "apollo-codegen-core/lib/utilities/CodeGenerator";
1010

@@ -15,6 +15,7 @@ import { generateSource as generateFlowSource } from "apollo-codegen-flow";
1515
import { generateSource as generateTypescriptSource } from "apollo-codegen-typescript";
1616
import { generateSource as generateScalaSource } from "apollo-codegen-scala";
1717
import { GraphQLSchema } from "graphql";
18+
import { FlowCompilerOptions } from '../../apollo-codegen-flow/lib/language';
1819

1920
export type TargetType =
2021
| "json"
@@ -27,15 +28,17 @@ export type TargetType =
2728
| "typescript"
2829
| "ts";
2930

31+
export type GenerationOptions = CompilerOptions & LegacyCompilerOptions & FlowCompilerOptions;
32+
3033
export default function generate(
3134
inputPaths: string[],
3235
schema: GraphQLSchema,
3336
outputPath: string,
34-
only: string,
37+
only: string | undefined,
3538
target: TargetType,
3639
tagName: string,
3740
nextToSources: boolean | string,
38-
options: any
41+
options: GenerationOptions
3942
): number {
4043
let writtenFiles = 0;
4144

@@ -159,14 +162,14 @@ interface OperationIdsMap {
159162
source: string;
160163
}
161164

162-
function writeOperationIdsMap(context: any) {
165+
function writeOperationIdsMap(context: CompilerContext) {
163166
let operationIdsMap: { [id: string]: OperationIdsMap } = {};
164167
Object.keys(context.operations)
165168
.map(k => context.operations[k])
166169
.forEach(operation => {
167-
operationIdsMap[operation.operationId] = {
170+
operationIdsMap[operation.operationId!] = {
168171
name: operation.operationName,
169-
source: operation.sourceWithFragments
172+
source: operation.source
170173
};
171174
});
172175
fs.writeFileSync(

packages/apollo-codegen-core/src/compiler/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ export interface CompilerOptions {
4141
customScalarsPrefix?: string;
4242
namespace?: string;
4343
generateOperationIds?: boolean;
44+
operationIdsPath?: string;
4445
}
4546

4647
export interface CompilerContext {

0 commit comments

Comments
 (0)