带有 Laravel Lighthouse return 字符串而不是 JSON 的 GraphQL 解析器

GraphQL resolver with Laravel Lighthouse return string instead of JSON

您好,我正在尝试创建一个 returns 和 JSON 的解析器,我将此库与自定义标量一起使用 https://github.com/mll-lab/graphql-php-scalars

我正在使用这样的 JSON 标量:

schema.graphql:

input CustomInput {
    field1: String!
    field2: String!
}

type Mutation {
    getJson(data: CustomInput): JSON @field(resolver: "App\GraphQL\Mutations\TestResolver@index")
}

TestResolver.php

public function index($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
{
   
    $data = array('msg'=>'hellow world', 'trueorfalse'=>true);
    return \Safe\json_encode($data);
    
}

GraphQL 游乐场

mutation{
 getJson(data: { field1: "foo", field2: "bar" })
}

------------ response------------
{
  "data": {
    "getJson": "\"{\\"msg\\":\\"hello world\\",\\"trueorfalse\\":true}\""
  }
}

as you can see it returns a string, instead of a JSON... what am I doing wrong?

你必须知道,你想收到什么回应。在解析器中,您必须 return 一个数组,因此在您的示例中只需 return $data.

接下来就是问题了,你期望...

  1. 您期望字符串化 JSON。然后你可以使用 JSON 来自 mll-lab/grpahql-php-scalars
  2. 的标量定义
  3. 您期望 JSON JS 对象方式。然后你必须使用不同的 JSON 标量定义。你可以试试这个:https://gist.github.com/lorado/0519972d6fcf01f1aa5179d09eb6a315

还有一个小改进:查询和变更不需要 @field 指令。如果您将字段的 CamelCased 名称放在特定命名空间中,Lighthouse 可以自动为您找到解析器(App\GraphQL\Queries 用于查询字段,App\GraphQL\Mutations 用于突变字段。这些是默认值,您可以在配置)。查看文档:https://lighthouse-php.com/master/the-basics/fields.html#hello-world

所以对于你的例子,你可以简单地写

type Mutation {
    getJson(data: CustomInput): JSON
}
<?php

namespace App\GraphQL\Mutations;

class GetJson
{
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $data = array('msg'=>'hellow world', 'trueorfalse'=>true);
        return $data;
    }
}