Arno van Oordt
Arno van Oordt

Reputation: 3520

GraphQL Default null value for Enums in Lighthouse

In Lighthouse I have an Enum like this

<?php

use GraphQL\Type\Definition\Description;

#[Description(description: 'Size')]

enum Size: string
{
    case M = 'm';
    case L = 'l';
}

In a service provider I register it like this:

    $typeRegistry->register(new PhpEnumType(Size::class));

In some input I want to use it like this:

input SomeInput {
    mySize: Size = null
    someOtherArgment: String = null
}

But making a mutation with this input gives me this error:

"message": "Undefined property: GraphQL\\Language\\AST\\NullValueNode::$value",
"exception": "ErrorException",
"file": "/var/www/html/vendor/nuwave/lighthouse/src/Schema/AST/ASTHelper.php",
"line": 166,

For some reason I can't set null as a default for any Enum values. If I omit the default null and just send null as value everything works fine so the fact that the Enum is null is not the issue, the null as default is the problem.

I tweaked the Nuwave\Lighthouse\Schema\AST\ASTHelper.php so that it now looks like this:

// if ($argumentType instanceof EnumType) {
if ($argumentType instanceof EnumType && !($defaultValue instanceof NullValueNode)) {
    assert($defaultValue instanceof EnumValueNode);

    $internalValue = $argumentType->getValue($defaultValue->value);
    assert($internalValue instanceof EnumValueDefinition);

    return $internalValue->value;
}

This simple tweak works perfect and I can now set null as a default without any issues, but since this requires me to alter the Lighthouse source code I'd like to finde a better alternative for this.

Is there a way to set an Enum's default to null without altering the source code or is this simply a bug in Lighthouse?

Upvotes: 0

Views: 114

Answers (1)

Arno van Oordt
Arno van Oordt

Reputation: 3520

After trying several possibilities with resolvers and directives to circumvent the issue I found that non of them were even close to a simple solution.

Instead I ended up making a copy and overwriting the ASTHelper.php using this method: Strategy to override a class in a library installed with Composer

Works great for now. Just need to be a bit carefull with any Lighthouse updates in the future.

Upvotes: 0

Related Questions