扩展灯塔指令

时间:2020-03-06 02:25:06

标签: laravel laravel-lighthouse

我想从灯塔库扩展指令@modelClass。 我正在开发模块化体系结构,没有Eloquent模型,有几个,并且正在扩展我的第一个Model版本,这就是为什么我使用接口绑定我需要的最后一个Model的原因。 我需要做的是使用接口代替模型类来解析我的类型对象。

使用指令@modelClass应该看起来像这样:

type User @modelClass(class: "App\\Models\\versionC\\User") {
  id: Int!
  username: String!
}

由于我具有此绑定:

$this->app->bind(UserInterface::class, User::class)

我应该有类似的东西

type User @modelClass(interface: "App\\Interfaces\\UserInterface") {
  id: Int!
  username: String!
}

但是我不能覆盖或扩展@modelClass指令。

1 个答案:

答案 0 :(得分:0)

我发现的解决方案是操纵模式

type User @entity(interface: "App\\Interfaces\\UserInterface") {
  id: Int!
  username: String!
}
class EntityDirective extends BaseDirective implements TypeManipulator
{
    public static function definition(): string
    {
        return /** @lang GraphQL */ <<<'SDL'
"""
Map an interface model class to an object type.
This can be used when an eloquent model it is bind to an interface.
"""
directive @entity(
    """
    The interface class name of the corresponding model binding.
    """
    interface: String!
) on OBJECT
SDL;
    }

    public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$objectType)
    {
        $modelClass = $this->directiveArgValue('interface');
        if(!$modelClass) {
            throw new DefinitionException(
                "An `interface` argument must be assigned to the '{$this->name()}'directive on '{$this->nodeName()}"
            );
        }

        $modelClass = get_class(resolve($modelClass));
        // If the type already exists, we use that instead
        if (isset($documentAST->types[$objectType->name->value])) {
            $objectType = $documentAST->types[$objectType->name->value];
        }

        $objectType->directives = ASTHelper::mergeNodeList(
            $objectType->directives,
            [PartialParser::directive('@modelClass(class: "'.addslashes($modelClass).'")')]
        );

        $documentAST->setTypeDefinition($objectType);
    }
}

记录我正在使用灯塔v4.10