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
30 changes: 28 additions & 2 deletions Sources/ApolloCodegenLib/ApolloCodegen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public class ApolloCodegen {
case invalidConfiguration(message: String)
case invalidSchemaName(_ name: String, message: String)
case targetNameConflict(name: String)
case typeNameConflict(name: String, conflictingName: String)

public var errorDescription: String? {
switch self {
Expand Down Expand Up @@ -53,8 +54,13 @@ public class ApolloCodegen {
return "The schema namespace `\(name)` is invalid: \(message)"
case let .targetNameConflict(name):
return """
Target name '\(name)' conflicts with a reserved library name. Please choose a different \
target name.
Target name '\(name)' conflicts with a reserved library name. Please choose a different \
target name.
"""
case let .typeNameConflict(name, conflictingName):
return """
Field '\(conflictingName)' conflicts with field '\(name)' in selection set. Recommend \
calvincestari marked this conversation as resolved.
Show resolved Hide resolved
using a field alias for one of these fields to resolve this conflict.
"""
}
}
Expand Down Expand Up @@ -212,6 +218,24 @@ public class ApolloCodegen {
throw Error.schemaNameConflict(name: context.schemaNamespace)
}
}

/// Validates that there are no type conflicts within a SelectionSet
static private func validateTypeConflicts(for selectionSet: IR.SelectionSet, with context: ConfigurationContext) throws {
calvincestari marked this conversation as resolved.
Show resolved Hide resolved
// Check for type conflicts resulting from singularization/pluralization of fields
var typeNames = [String: String]()
calvincestari marked this conversation as resolved.
Show resolved Hide resolved
var fields: [IR.EntityField] = selectionSet.selections.direct?.fields.values.compactMap({ $0 as? IR.EntityField }) ?? []
fields.append(contentsOf: selectionSet.selections.merged.fields.values.compactMap({ $0 as? IR.EntityField }))

try fields.forEach({ field in
calvincestari marked this conversation as resolved.
Show resolved Hide resolved
let formattedTypeName = field.formattedSelectionSetName(with: context.pluralizer)
if let existingFieldName = typeNames[formattedTypeName] {
throw Error.typeNameConflict(name: existingFieldName, conflictingName: field.name)
}

typeNames[formattedTypeName] = field.name
try validateTypeConflicts(for: field.selectionSet, with: context)
})
}

/// Performs GraphQL source validation and compiles the schema and operation source documents.
static func compileGraphQLResult(
Expand Down Expand Up @@ -304,6 +328,7 @@ public class ApolloCodegen {
for fragment in compilationResult.fragments {
try autoreleasepool {
let irFragment = ir.build(fragment: fragment)
try validateTypeConflicts(for: irFragment.rootField.selectionSet, with: config)
calvincestari marked this conversation as resolved.
Show resolved Hide resolved
try FragmentFileGenerator(irFragment: irFragment, config: config)
.generate(forConfig: config, fileManager: fileManager)
}
Expand All @@ -314,6 +339,7 @@ public class ApolloCodegen {
for operation in compilationResult.operations {
try autoreleasepool {
let irOperation = ir.build(operation: operation)
try validateTypeConflicts(for: irOperation.rootField.selectionSet, with: config)
try OperationFileGenerator(irOperation: irOperation, config: config)
.generate(forConfig: config, fileManager: fileManager)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ fileprivate extension IR.SelectionSet {

}

fileprivate extension IR.EntityField {
extension IR.EntityField {
calvincestari marked this conversation as resolved.
Show resolved Hide resolved

func formattedSelectionSetName(
with pluralizer: Pluralizer
Expand Down
72 changes: 72 additions & 0 deletions Tests/ApolloCodegenTests/ApolloCodegenTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2334,6 +2334,78 @@ class ApolloCodegenTests: XCTestCase {
// then
expect(try ApolloCodegen._validate(config: config)).notTo(throwError())
}

func test__validation__selectionSet_typeConflicts_shouldThrowError() throws {
calvincestari marked this conversation as resolved.
Show resolved Hide resolved
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
}

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) = error else {
fail("Expected .typeNameConflict, got .\(error)")
return
}
expect(name).to(equal("value"))
expect(conflictingName).to(equal("values"))
})
}

// MARK: Path Match Exclusion Tests

Expand Down