0

I have notification table , where data field stored as json :

{"data":{"description":"Event Status has been changed to pending","event_id":19}}

I get this error

"errors": [
{
  "debugMessage": "Expected a value of type \"String\" but received: {\"data\":{\"description\":\"Event Status has been changed to pending\",\"event_id\":19}}",

I have tried to add the following on notifications model:

public function getDataAttribute($data)
{
    return json_decode($data, true);
}

But no solution.

I tried to use [String] in GraphQL schema but nothing.

Alex
  • 1,425
  • 11
  • 25
  • you'r trying to return object/array/record - [complex] separate type in graphql - as single string? no way ... use **custom json scalar** https://stackoverflow.com/a/62647404/6124657 ? – xadm May 13 '21 at 09:29

2 Answers2

0

If you want arbitrary JSON data to be returned as a string there are 2 options:

The first is to use a JSON scalar, you can either built your own or use a composer package. It wil encode the data to a valid JSON string.

The second option is to make sure you are returning just the JSON and not the decoded JSON. I'm assuming your data is already decoded to JSON because you are using model casts, if not you could just remove the json_decode call. You could add a getter to re-encode it back to JSON or add a getter to get the value from the attributes property on your model.

public function getRawDataAttribute(): string
{
    return $this->attributes['data'];
}

// or

public function getRawDataAttribute(): string
{
     return json_encode($this->data);
}

You can use this in your schema like this:

type MyType {
    data: String! @rename(attribute: "raw_data")
}

But the first option is definitely the easiest and the best in my opinion because it correctly indicates in the schema the field contains JSON and handles the encoding (and decoding when used in inputs) for you.

Alex
  • 1,425
  • 11
  • 25
0

Add this package for implementing JSON type to your app:

https://github.com/mll-lab/graphql-php-scalars

then add this line to your schema.graphql file:

scalar JSON @scalar(class: "MLL\\GraphQLScalars\\JSON")

After than you can easily use JSON type like this:

type MyType {
    data: JSON! @rename(attribute: "raw_data")
}
Alireza A2F
  • 519
  • 4
  • 26