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

Php 带有Laravel Lighthouse返回字符串而不是JSON的GraphQL解析器,php,laravel,graphql,laravel-lighthouse,Php,Laravel,Graphql,Laravel Lighthouse,嗨,我正在尝试创建一个返回JSON的解析器,我使用这个库和自定义标量 我使用的JSON标量如下: schema.graphql: input CustomInput { field1: String! field2: String! } type Mutation { getJson(data: CustomInput): JSON @field(resolver: "App\\GraphQL\\Mutations\\TestResolver@index&qu

嗨,我正在尝试创建一个返回JSON的解析器,我使用这个库和自定义标量

我使用的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 PlayGround

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

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

正如您所看到的,它返回一个字符串,而不是JSON。。。我做错了什么


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

然后是问题,你期待什么

  • 您需要一个字符串化的JSON。然后您可以使用
    mll-lab/grpahql-php标量中的JSON标量定义
  • 您希望JSON采用JS对象方式。然后必须使用不同的JSON标量定义。你可以试试这个:

  • 还有一个小小的改进:查询和突变不需要
    @field
    指令。Lighthouse可以自动为您找到解析程序,如果您在特定命名空间中放置字段的CamelCased名称(
    App\GraphQL\querys
    用于查询字段,而
    App\GraphQL\translations
    用于突变字段。这些是默认值,您可以在配置中更改它们)。查看文档:

    例如,你可以简单地写

    type Mutation {
        getJson(data: CustomInput): JSON
    }
    

    just
    return$data
    ?@xadm返回字符串,但现在像这样
    “{\“msg\”:“hello world\”,“trueorfalse\”:true}”
    哇,回答得太好了!非常好,谢谢♥