为了账号安全,请及时绑定邮箱和手机立即绑定

GraphQL 解析器使用 Laravel Lighthouse 返回字符串而不是 JSON

GraphQL 解析器使用 Laravel Lighthouse 返回字符串而不是 JSON

PHP
繁星点点滴滴 2023-07-07 10:55:58
您好,我正在尝试创建一个返回 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")}测试解析器.phppublic 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}\""  }}正如你所看到的,它返回一个字符串,而不是 JSON...我做错了什么?
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

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

那么问题来了,你期望什么...

  1. 您期望得到一个字符串化的 JSON。然后你可以使用 JSON 标量定义mll-lab/grpahql-php-scalars

  2. 您期望 JS 对象方式的 JSON。然后你必须使用不同的 JSON 标量定义。


对您来说还有一个小改进:查询和突变不需要@field指令。如果您将字段的 CamelCased 名称放置在特定名称空间中(App\GraphQL\Queries对于查询字段和App\GraphQL\Mutations突变字段。这些是默认值,您可以在配置中更改它们),Lighthouse 可以自动为您找到解析器。

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

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;

    }

}


查看完整回答
反对 回复 2023-07-07
  • 1 回答
  • 0 关注
  • 134 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信