如何从MutationResolver结果中调用TypeResolver?

时间:2019-10-18 04:08:40

标签: laravel graphql

我创建了一个变异,该变异将一些记录插入数据库中,我希望将结果传递给相应的类型解析器,以便对结果进行格式化(客户端期望使用驼峰格式),并且客户端也可以查询嵌套数据(如果有)。

我正在使用laravel +一个针对graphql(rebing)的包装器

我的变异如下:

class CreateIngressedAccountsMutation extends Mutation
{    
    protected $attributes = [
        'name' => 'createIngressedAccounts'
    ];

    public function type(): Type
    {
        return Type::nonNull(Type::listOf(GraphQL::type('IngressedAccount')));
    }

    public function args(): array
    {
        return [
            'accounts' => ['type' => Type::nonNull(Type::listOf(GraphQL::type('CreateIngressedAccountInput')))]
        ];
    }


    public function resolve($root, $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
    {
        $accounts = collect($args['accounts']);

        return DB::transaction(function () use ($accounts) {
            return $accounts->map(function ($accountInput) {
                $account = (new IngressedAccount())->fill($accountInput));
                $account->saveOrFail();

                // some logic
                // ...

                // the client expects camel case, so I have to manually include the properties,
                // the IngressedAccountType does it through alias
                $account['createdBy'] = $account->created_by;
                $account['createdAt'] = $account->created_at;
                $account['updatedAt'] = $account->updated_at;
                return $account;
            });
        });


        return $result;
    }
}

我的IngressedAccountType如下:

class IngressedAccountType extends GraphQLType
{
    protected $attributes = ['name' => 'IngressedAccount',];

    public function fields(): array
    {
        return [
            'id' => ['type' => Type::nonNull(Type::id())],
            'visitId' => ['type' => Type::nonNull(Type::id()), 'alias' => 'visit_id'],
            'createdBy' => ['type' => Type::nonNull(Type::id())],
            'name' => ['type' => Type::nonNull(Type::string())],
            'type' => ['type' => Type::nonNull(Type::string())],
            'geolocation' => ['type' => Type::nonNull(Type::string())],
            'createdAt' => ['type' => Type::nonNull(Type::string()), 'alias' => 'created_at'],
            'updatedAt' => ['type' => Type::string(), 'alias' => 'updated_at'],

            'visit' => ['type' => Type::nonNull(GraphQL::type('User'))],
            'comments' => ['type' => Type::nonNull(Type::listOf(Type::nonNull(GraphQL::type('Comment'))))]
        ];
    }

    protected function resolveCommentsField($root, $args)
    {
        return Comment::query()->where('entity_id', $root->id)->where('entity_name', 'ingressed_account')->get();
    }
}

0 个答案:

没有答案