Skip to content

Commit 1e484af

Browse files
author
Dane Pilcher
authored
fix: generate multiple swift files in graphql-generator (#718)
1 parent e33eb4a commit 1e484af

File tree

9 files changed

+306
-716
lines changed

9 files changed

+306
-716
lines changed

packages/amplify-codegen/src/commands/types.js

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@ const path = require('path');
22
const fs = require('fs-extra');
33
const Ora = require('ora');
44
const glob = require('glob-all');
5+
const { Source } = require('graphql');
56

67
const constants = require('../constants');
78
const { loadConfig } = require('../codegen-config');
89
const { ensureIntrospectionSchema, getFrontEndHandler, getAppSyncAPIDetails, getAppSyncAPIInfoFromProject } = require('../utils');
910
const { generateTypes: generateTypesHelper } = require('@aws-amplify/graphql-generator');
10-
const { generate, extractDocumentFromJavascript } = require('@aws-amplify/graphql-types-generator');
11+
const { extractDocumentFromJavascript } = require('@aws-amplify/graphql-types-generator');
1112

1213
async function generateTypes(context, forceDownloadSchema, withoutInit = false, decoupleFrontend = '') {
1314
let frontend = decoupleFrontend;
@@ -61,7 +62,7 @@ async function generateTypes(context, forceDownloadSchema, withoutInit = false,
6162
cwd: projectPath,
6263
absolute: true,
6364
});
64-
const queryFiles = queryFilePaths.map(queryFilePath => {
65+
const queries = queryFilePaths.map(queryFilePath => {
6566
const fileContents = fs.readFileSync(queryFilePath, 'utf8');
6667
if (
6768
queryFilePath.endsWith('.jsx') ||
@@ -71,12 +72,11 @@ async function generateTypes(context, forceDownloadSchema, withoutInit = false,
7172
) {
7273
return extractDocumentFromJavascript(fileContents, '');
7374
}
74-
return fileContents;
75+
return new Source(fileContents, queryFilePath);
7576
});
76-
if (queryFiles.length === 0) {
77+
if (queries.length === 0) {
7778
throw new Error("No queries found to generate types for, you may need to run 'codegen statements' first");
7879
}
79-
const queries = queryFiles.join('\n');
8080

8181
const schemaPath = path.join(projectPath, cfg.schema);
8282

@@ -93,32 +93,25 @@ async function generateTypes(context, forceDownloadSchema, withoutInit = false,
9393
codeGenSpinner.start();
9494
const schema = fs.readFileSync(schemaPath, 'utf8');
9595
const introspection = path.extname(schemaPath) === '.json';
96-
96+
const multipleSwiftFiles = target === 'swift' && fs.existsSync(outputPath) && fs.statSync(outputPath).isDirectory();
9797
try {
98-
if (target === 'swift' && fs.existsSync(outputPath) && fs.statSync(outputPath).isDirectory()) {
99-
generate(queryFilePaths, schemaPath, outputPath, '', target, '', {
100-
addTypename: true,
101-
complexObjectSupport: 'auto',
102-
});
98+
const output = await generateTypesHelper({
99+
schema,
100+
queries,
101+
target,
102+
introspection,
103+
multipleSwiftFiles,
104+
});
105+
const outputs = Object.entries(output);
106+
107+
const outputPath = path.join(projectPath, generatedFileName);
108+
if (outputs.length === 1) {
109+
const [[, contents]] = outputs;
110+
fs.outputFileSync(path.resolve(outputPath), contents);
103111
} else {
104-
const output = await generateTypesHelper({
105-
schema,
106-
queries,
107-
target,
108-
introspection,
109-
multipleSwiftFiles: false,
112+
outputs.forEach(([filepath, contents]) => {
113+
fs.outputFileSync(path.resolve(path.join(outputPath, filepath)), contents);
110114
});
111-
const outputs = Object.entries(output);
112-
113-
const outputPath = path.join(projectPath, generatedFileName);
114-
if (outputs.length === 1) {
115-
const [[, contents]] = outputs;
116-
fs.outputFileSync(path.resolve(outputPath), contents);
117-
} else {
118-
outputs.forEach(([filepath, contents]) => {
119-
fs.outputFileSync(path.resolve(path.join(outputPath, filepath)), contents);
120-
});
121-
}
122115
}
123116
codeGenSpinner.succeed(`${constants.INFO_MESSAGE_CODEGEN_GENERATE_SUCCESS} ${path.relative(path.resolve('.'), outputPath)}`);
124117
} catch (err) {

packages/amplify-codegen/tests/commands/types.test.js

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
const { sync } = require('glob-all');
22
const path = require('path');
33
const { generateTypes: generateTypesHelper } = require('@aws-amplify/graphql-generator');
4-
const { generate: legacyGenerate } = require('@aws-amplify/graphql-types-generator');
54
const fs = require('fs-extra');
5+
const { Source } = require('graphql');
66

77
const { loadConfig } = require('../../src/codegen-config');
88
const generateTypes = require('../../src/commands/types');
@@ -60,6 +60,9 @@ describe('command - types', () => {
6060
beforeEach(() => {
6161
jest.clearAllMocks();
6262
fs.existsSync.mockReturnValue(true);
63+
fs.statSync.mockReturnValue({
64+
isDirectory: jest.fn().mockReturnValue(false),
65+
});
6366
getFrontEndHandler.mockReturnValue('javascript');
6467
loadConfig.mockReturnValue({
6568
getProjects: jest.fn().mockReturnValue([MOCK_PROJECT]),
@@ -79,15 +82,15 @@ describe('command - types', () => {
7982
expect(loadConfig).toHaveBeenCalledWith(MOCK_CONTEXT, false);
8083
expect(sync).toHaveBeenCalledWith([MOCK_INCLUDE_PATH, `!${MOCK_EXCLUDE_PATH}`], { cwd: MOCK_PROJECT_ROOT, absolute: true });
8184
expect(generateTypesHelper).toHaveBeenCalledWith({
82-
queries: 'query 1\nquery 2',
85+
queries: [new Source('query 1', 'q1.gql'), new Source('query 2', 'q2.gql')],
8386
schema: 'schema',
8487
target: 'TYPE_SCRIPT_OR_FLOW_OR_ANY_OTHER_LANGUAGE',
8588
introspection: false,
8689
multipleSwiftFiles: false,
8790
});
8891
});
8992

90-
it('should use legacy types generation when generating multiple swift files', async () => {
93+
it('should use generate multiple swift files', async () => {
9194
MOCK_PROJECT.amplifyExtension.codeGenTarget = 'swift';
9295
MOCK_PROJECT.amplifyExtension.generatedFileName = 'typesDirectory';
9396
const forceDownload = false;
@@ -100,16 +103,6 @@ describe('command - types', () => {
100103
isDirectory: jest.fn().mockReturnValue(true),
101104
});
102105
await generateTypes(MOCK_CONTEXT, forceDownload);
103-
expect(generateTypesHelper).not.toHaveBeenCalled();
104-
expect(legacyGenerate).toHaveBeenCalledWith(
105-
['q1.gql', 'q2.gql'],
106-
'MOCK_PROJECT_ROOT/INTROSPECTION_SCHEMA.JSON',
107-
'MOCK_PROJECT_ROOT/typesDirectory',
108-
'',
109-
'swift',
110-
'',
111-
{ addTypename: true, complexObjectSupport: 'auto' },
112-
);
113106
});
114107

115108
it('should not generate type if the frontend is android', async () => {
@@ -121,6 +114,7 @@ describe('command - types', () => {
121114

122115
it('should download the schema if forceDownload flag is passed', async () => {
123116
const forceDownload = true;
117+
fs.readFileSync.mockReturnValueOnce('query 1').mockReturnValueOnce('query 2');
124118
await generateTypes(MOCK_CONTEXT, forceDownload);
125119
expect(ensureIntrospectionSchema).toHaveBeenCalledWith(
126120
MOCK_CONTEXT,
@@ -134,6 +128,7 @@ describe('command - types', () => {
134128
it('should download the schema if the schema file is missing', async () => {
135129
fs.existsSync.mockReturnValue(false);
136130
const forceDownload = false;
131+
fs.readFileSync.mockReturnValueOnce('query 1').mockReturnValueOnce('query 2');
137132
await generateTypes(MOCK_CONTEXT, forceDownload);
138133
expect(ensureIntrospectionSchema).toHaveBeenCalledWith(
139134
MOCK_CONTEXT,

packages/graphql-generator/API.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
55
```ts
66

7+
import { Source } from 'graphql';
78
import { Target } from '@aws-amplify/appsync-modelgen-plugin';
89
import { Target as Target_2 } from '@aws-amplify/graphql-types-generator';
910

@@ -49,7 +50,7 @@ export function generateTypes(options: GenerateTypesOptions): Promise<GeneratedO
4950
export type GenerateTypesOptions = {
5051
schema: string;
5152
target: TypesTarget;
52-
queries: string;
53+
queries: string | Source[];
5354
introspection?: boolean;
5455
multipleSwiftFiles?: boolean;
5556
};

0 commit comments

Comments
 (0)