GraphQL resolver with Laravel Lighthouse return string instead of JSON

Viewed 4217

Hi I'm trying to create a resolver that returns a JSON, I use this library with custom scalars https://github.com/mll-lab/graphql-php-scalars

I'm using the JSON scalar like this:

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 Playgroud

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?

1 Answers

You have to know, what you want to receive in response. In resolver you have to return an array, so in your example simply return $data.

Then is the question, what you expect...

  1. You expect a stringified JSON. Then you can use JSON scalar definition from mll-lab/grpahql-php-scalars
  2. You expect a JSON in JS object manner. Then you have to use different JSON Scalar definition. You can try this one: https://gist.github.com/lorado/0519972d6fcf01f1aa5179d09eb6a315

Also a small improvement for you: queries and mutations don't need @field directive. Lighthouse can find a resolver for you automatically, if you place a CamelCased name of the field in a specific namespace (App\GraphQL\Queries for query fields and App\GraphQL\Mutations for mutation fields. These are defaults, you may change them in config). Take a look into the docs: https://lighthouse-php.com/master/the-basics/fields.html#hello-world

So for you example you can simply write

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;
    }
}
Related