From eee1ee8814b2ab3031446551ac5b00231c1ee9c0 Mon Sep 17 00:00:00 2001 From: Jay Herron Date: Wed, 23 Oct 2024 23:46:48 -0600 Subject: [PATCH] fix: Allows numeric values to be parsed as Bools This is because MapCoder round-trips of Bools result in Number types. This is hard to avoid since it gets put into an NSObject container and there is no NSBool type. --- Sources/GraphQL/Type/Scalars.swift | 5 +++++ Tests/GraphQLTests/TypeTests/ScalarTests.swift | 18 ++++++------------ 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/Sources/GraphQL/Type/Scalars.swift b/Sources/GraphQL/Type/Scalars.swift index 7deafd15..e5f9a0d2 100644 --- a/Sources/GraphQL/Type/Scalars.swift +++ b/Sources/GraphQL/Type/Scalars.swift @@ -201,6 +201,11 @@ public let GraphQLBoolean = try! GraphQLScalarType( if case let .bool(value) = inputValue { return inputValue } + // NOTE: We deviate from graphql-js and allow numeric conversions here because + // the MapCoder's round-trip conversion to NSObject for Bool converts to 0/1 numbers. + if case let .number(value) = inputValue { + return .bool(value.intValue != 0) + } throw GraphQLError( message: "Boolean cannot represent a non boolean value: \(inputValue)" ) diff --git a/Tests/GraphQLTests/TypeTests/ScalarTests.swift b/Tests/GraphQLTests/TypeTests/ScalarTests.swift index a409ea21..59bc6e87 100644 --- a/Tests/GraphQLTests/TypeTests/ScalarTests.swift +++ b/Tests/GraphQLTests/TypeTests/ScalarTests.swift @@ -300,18 +300,12 @@ class ScalarTests: XCTestCase { GraphQLBoolean.parseValue(.null), "Boolean cannot represent a non boolean value: null" ) - try XCTAssertThrowsError( - GraphQLBoolean.parseValue(0), - "Boolean cannot represent a non boolean value: 0" - ) - try XCTAssertThrowsError( - GraphQLBoolean.parseValue(1), - "Boolean cannot represent a non boolean value: 1" - ) - try XCTAssertThrowsError( - GraphQLBoolean.parseValue(.double(Double.nan)), - "Boolean cannot represent a non boolean value: NaN" - ) + // NOTE: We deviate from graphql-js and allow numeric conversions here because + // the MapCoder's round-trip conversion to NSObject for Bool converts to 0/1 numbers. + try XCTAssertNoThrow(GraphQLBoolean.parseValue(0)) + try XCTAssertNoThrow(GraphQLBoolean.parseValue(1)) + try XCTAssertNoThrow(GraphQLBoolean.parseValue(.double(Double.nan))) + try XCTAssertThrowsError( GraphQLBoolean.parseValue(""), #"Boolean cannot represent a non boolean value: """#