Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check type name conflicts in SelectionSet #3009

Merged
merged 6 commits into from
May 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Sources/ApolloCodegenLib/ApolloCodegen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ public class ApolloCodegen {
"""
case let .typeNameConflict(name, conflictingName, containingObject):
return """
TypeNameConflict - \
Field '\(conflictingName)' conflicts with field '\(name)' in operation/fragment `\(containingObject)`. \
Recommend using a field alias for one of these fields to resolve this conflict.
Recommend using a field alias for one of these fields to resolve this conflict. \
For more info see: https://www.apollographql.com/docs/ios/troubleshooting/codegen-troubleshooting#typenameconflict
"""
}
}
Expand Down Expand Up @@ -243,8 +245,6 @@ public class ApolloCodegen {
// gather nested fragments to loop through and check as well
var nestedSelectionSets: [IR.SelectionSet] = selectionSet.selections.direct?.inlineFragments.values.elements ?? []
nestedSelectionSets.append(contentsOf: selectionSet.selections.merged.inlineFragments.values)
nestedSelectionSets.append(contentsOf: selectionSet.selections.direct?.fragments.values.map { $0.fragment.rootField.selectionSet } ?? [])
calvincestari marked this conversation as resolved.
Show resolved Hide resolved
nestedSelectionSets.append(contentsOf: selectionSet.selections.merged.fragments.values.map { $0.fragment.rootField.selectionSet })

try nestedSelectionSets.forEach { nestedSet in
try validateTypeConflicts(for: nestedSet, with: context, in: containingObject)
Expand Down
223 changes: 222 additions & 1 deletion Tests/ApolloCodegenTests/ApolloCodegenTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2408,7 +2408,7 @@ class ApolloCodegenTests: XCTestCase {
})
}

func test__validation__selectionSet_typeConflicts_withMergedFragments_shouldThrowError() throws {
func test__validation__selectionSet_typeConflicts_withDirectInlineFragment_shouldThrowError() throws {
let schemaDefData: Data = {
"""
type Query {
Expand Down Expand Up @@ -2481,6 +2481,227 @@ class ApolloCodegenTests: XCTestCase {
expect(containingObject).to(equal("ConflictingQuery"))
})
}

func test__validation__selectionSet_typeConflicts_withMergedInlineFragment_shouldThrowError() throws {
let schemaDefData: Data = {
"""
type Query {
user: UserInterface
}
type User implements UserInterface {
containers: [ContainerInterface]
}
interface UserInterface {
containers: [ContainerInterface]
}
interface ContainerInterface {
value: Value
}
type Container implements ContainerInterface {
value: Value
values: [Value]
}
type Value {
propertyA: String!
propertyB: String!
propertyC: String!
propertyD: String!
}
"""
}().data(using: .utf8)!

let operationData: Data =
"""
query ConflictingQuery {
user {
containers {
value {
propertyA
propertyB
propertyC
propertyD
}
}
... on User {
containers {
... on Container {
values {
propertyA
propertyC
}
}
}
}
}
}
""".data(using: .utf8)!

try createFile(containing: schemaDefData, named: "schema.graphqls")
try createFile(containing: operationData, named: "operation.graphql")

let config = ApolloCodegenConfiguration.mock(
input: .init(
schemaSearchPaths: ["schema*.graphqls"],
operationSearchPaths: ["*.graphql"]
),
output: .init(
schemaTypes: .init(path: "SchemaModule",
moduleType: .swiftPackageManager),
operations: .inSchemaModule
)
)

expect(try ApolloCodegen.build(with: config))
.to(throwError { error in
guard case let ApolloCodegen.Error.typeNameConflict(name, conflictingName, containingObject) = error else {
fail("Expected .typeNameConflict, got .\(error)")
return
}
expect(name).to(equal("values"))
expect(conflictingName).to(equal("value"))
expect(containingObject).to(equal("ConflictingQuery"))
})
}

func test__validation__selectionSet_typeConflicts_withDirectNamedFragment_shouldThrowError() throws {
let schemaDefData: Data = {
"""
type Query {
user: User
}
type User {
containers: [Container]
}

type Container {
value: Value
values: [Value]
}
type Value {
propertyA: String!
propertyB: String!
propertyC: String!
propertyD: String!
}
"""
}().data(using: .utf8)!

let operationData: Data =
"""
query ConflictingQuery {
user {
containers {
value {
propertyA
propertyB
propertyC
propertyD
}
...ContainerFields
}
}
}

fragment ContainerFields on Container {
values {
propertyA
propertyC
}
}
""".data(using: .utf8)!

try createFile(containing: schemaDefData, named: "schema.graphqls")
try createFile(containing: operationData, named: "operation.graphql")

let config = ApolloCodegenConfiguration.mock(
input: .init(
schemaSearchPaths: ["schema*.graphqls"],
operationSearchPaths: ["*.graphql"]
),
output: .init(
schemaTypes: .init(path: "SchemaModule",
moduleType: .swiftPackageManager),
operations: .inSchemaModule
)
)

expect(try ApolloCodegen.build(with: config))
.to(throwError { error in
guard case let ApolloCodegen.Error.typeNameConflict(name, conflictingName, containingObject) = error else {
fail("Expected .typeNameConflict, got .\(error)")
return
}
expect(name).to(equal("value"))
expect(conflictingName).to(equal("values"))
expect(containingObject).to(equal("ConflictingQuery"))
})
}

func test__validation__selectionSet_typeConflicts_withNamedFragment_shouldThrowError() throws {
let schemaDefData: Data = {
"""
type Query {
user: User
}
type User {
containers: [Container]
}

type Container {
value: Value
values: [Value]
}
type Value {
propertyA: String!
propertyB: String!
propertyC: String!
propertyD: String!
}
"""
}().data(using: .utf8)!

let operationData: Data =
"""
fragment ContainerFields on Container {
value {
propertyA
propertyB
propertyC
propertyD
}
values {
propertyA
propertyC
}
}
""".data(using: .utf8)!

try createFile(containing: schemaDefData, named: "schema.graphqls")
try createFile(containing: operationData, named: "operation.graphql")

let config = ApolloCodegenConfiguration.mock(
input: .init(
schemaSearchPaths: ["schema*.graphqls"],
operationSearchPaths: ["*.graphql"]
),
output: .init(
schemaTypes: .init(path: "SchemaModule",
moduleType: .swiftPackageManager),
operations: .inSchemaModule
)
)

expect(try ApolloCodegen.build(with: config))
.to(throwError { error in
guard case let ApolloCodegen.Error.typeNameConflict(name, conflictingName, containingObject) = error else {
fail("Expected .typeNameConflict, got .\(error)")
return
}
expect(name).to(equal("value"))
expect(conflictingName).to(equal("values"))
expect(containingObject).to(equal("ContainerFields"))
})
}

// MARK: Path Match Exclusion Tests

Expand Down
3 changes: 3 additions & 0 deletions docs/source/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@
},
"Development & Testing": {
"Test Mocks": "/testing/test-mocks"
},
"Troubleshooting": {
"Code Generation": "/troubleshooting/codegen-troubleshooting"
}
}
}
88 changes: 88 additions & 0 deletions docs/source/troubleshooting/codegen-troubleshooting.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
---
title: Code Generation Troubleshooting
sidebar_title: Code Generation
---

# Errors

## TypeNameConflict

Example error output:

```text title="TypeNameConflict error output"
TypeNameConflict - Field 'values' conflicts with field 'value' in operation/fragment `ConflictingQuery`. Recommend using a field alias for one of these fields to resolve this conflict.
```

If you receive this error, you have an Operation or Fragment that is resulting in multiple types of the same name due to how singularization/pluralization works in code generation. Take the following schema and query defintion for example:

```graphql title="Example Schema"
type Query {
user: User
}

type User {
containers: [Container]
}

type Container {
value: Value
values: [Value]
}

type Value {
propertyA: String!
propertyB: String!
propertyC: String!
propertyD: String!
}
```

```graphql title="ConflictingQuery"
query ConflictingQuery {
user {
containers {
value {
propertyA
propertyB
propertyC
propertyD
}

values {
propertyA
propertyC
}
}
}
}
```

If you run code generation with these you will get the `TypeNameConflict` error because the generated code for your query would contain code that looks like this:

<img class="screenshot" src="images/type_name_conflict_example_output.png" alt="TypeNameConflict example code output" />

As the error says, the recommended way to solve this is to use a field alias, so updating the query to be this:

```graphql title="ConflictingQuery"
query ConflictingQuery {
user {
containers {
value {
propertyA
propertyB
propertyC
propertyD
}

valueAlias: values {
propertyA
propertyC
}
}
}
}
```

If you run the code generation with the update query you will no longer see the error and the resulting code will look like this:

<img class="screenshot" src="images/type_name_conflict_alias_output.png" alt="TypeNameConflict alias example code output" />
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.