Skip to content

Commit ff2c8e4

Browse files
Include namespace in fragment struct type names
to make sure that if the fragment is used in a query that has a node (and therefore type name) with the same name as the fragment's type name, Swift doesn't get confused about which type is being referred to.
1 parent c05c9e4 commit ff2c8e4

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
- `apollo-codegen-scala`
1212
- <First `apollo-codegen-scala` related entry goes here>
1313
- `apollo-codegen-swift`
14-
- <First `apollo-codegen-swift` related entry goes here>
14+
- Add namespace when a fragment struct is referenced (Fixes #2396) [PR #2397](https://github.com/apollographql/apollo-tooling/pull/2397)
1515
- `apollo-codegen-typescript`
1616
- <First `apollo-codegen-typescript` related entry goes here>
1717
- `apollo-codegen-core`

packages/apollo-codegen-swift/src/codeGeneration.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,9 @@ export class SwiftAPIGenerator extends SwiftGenerator<CompilerContext> {
339339
outputIndividualFiles: boolean,
340340
suppressMultilineStringLiterals: boolean
341341
) {
342-
const structName = this.helpers.structNameForFragmentName(fragmentName);
342+
const structName = this.helpers.structDeclarationNameForFragmentName(
343+
fragmentName
344+
);
343345

344346
this.structDeclarationForSelectionSet(
345347
{

packages/apollo-codegen-swift/src/helpers.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,22 @@ export class Helpers {
125125
return pascalCase(Inflector.singularize(propertyName));
126126
}
127127

128+
/**
129+
* Returns the Swift name for a struct representing a fragment. This must contain
130+
* the application namespace in case the fragment name is the same as the name of any
131+
* field in the current query, otherwise, Swift will assume the type reference is to
132+
* the struct that we're inside the namespace of.
133+
*/
128134
structNameForFragmentName(fragmentName: string) {
135+
const prefix = this.options?.namespace ? `${this.options.namespace}.` : "";
136+
return `${prefix}${pascalCase(fragmentName)}`;
137+
}
138+
139+
/**
140+
* Returns the Swift struct name that is being declared. When declaring a struct in Swift,
141+
* no namespace can be included in the name.
142+
*/
143+
structDeclarationNameForFragmentName(fragmentName: string) {
129144
return pascalCase(fragmentName);
130145
}
131146

0 commit comments

Comments
 (0)