(Potentially Breaking) Allow serializing scalars as null.

This changes the check for null/undefined to a check for undefined to determine if scalar serialization was successful or not, allowing `null` to be returned from serialize() without indicating error.

This is potentially breaking for any existing custom scalar which returned `null` from `serialize()` to indicate failure. To account for this change, it should either throw an error or return `undefined`.

ref: graphql/graphql-js#1104
This commit is contained in:
Daniel Tschinder 2018-02-09 14:30:05 +01:00
parent 27ce24b5fe
commit 48c33302a8
3 changed files with 13 additions and 9 deletions

View File

@ -1187,7 +1187,7 @@ class Executor
{
$serializedResult = $returnType->serialize($result);
if ($serializedResult === null) {
if (Utils::isInvalid($serializedResult)) {
throw new InvariantViolation(
'Expected a value of type "'. Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result)
);

View File

@ -108,7 +108,11 @@ class EnumType extends Type implements InputType, OutputType, LeafType
public function serialize($value)
{
$lookup = $this->getValueLookup();
return isset($lookup[$value]) ? $lookup[$value]->name : null;
if (isset($lookup[$value])) {
return $lookup[$value]->name;
}
return Utils::undefined();
}
/**

View File

@ -205,15 +205,15 @@ class AST
return new ObjectValueNode(['fields' => $fieldNodes]);
}
Utils::invariant(
$type instanceof ScalarType || $type instanceof EnumType,
"Must provide Input Type, cannot use: " . Utils::printSafe($type)
);
// Since value is an internally represented value, it must be serialized
// to an externally represented value before converting into an AST.
if ($type instanceof LeafType) {
$serialized = $type->serialize($value);
} else {
throw new InvariantViolation("Must provide Input Type, cannot use: " . Utils::printSafe($type));
}
if (null === $serialized) {
$serialized = $type->serialize($value);
if (null === $serialized || Utils::isInvalid($serialized)) {
return null;
}