0

I do not know how to ask but I summarize what I want to do. I have a laravel server with lighthouse I do not handle databases or models, my data source is an api that returns the data in a json, now my query is how do I convert or map the json for a graphql query?

the structure of my json is more or less like this:

{
    "order" : 
    [
        {
            "details":
            {
              "id": "file",  
              "value": "File"
            }
        },
        {
            "menu":
            {
              "menuitem":
              [
                {"value": "New", "onclick": "CreateDoc()"},  
                {"value": "Open", "onclick": "OpenDoc()"},  
                {"value": "Save", "onclick": "SaveDoc()"}
              ]
            }
        }
    ]
}

and the structure of my schematic is something like this:

type order {
  details: details
  menu: menu

}

type details {
  id: String
  value: String
}

type menu {
  menuitem: menuitem
}

type menuitem {
  value: String
  onclick: String
}

type query {
  orders: [order]
}

the solution is for the custom resolver or the eloquent models or something else, if someone could guide me it would be very helpful

1 Answers1

0

You can just return an array with the shape of your GraphQL types. I mean, if your custom resolver return something like this, it will work:

<?php

class CustomResolver {
    public function __invoke($root, array $args) 
    {
        return [
            'menu' => [
                'menuitems' => [
                    ['value' => 'New', 'onclick' => 'CreateDoc()'],
                ],
            ],
        ];
    }
}

But you also have to modify your menu type to include an array of menuitems:

type menu {
  menuitem: [menuitem!]
}

So, basically, just transform the response of your api to the shape that GraphQL types expects.

Enzo Notario
  • 639
  • 4
  • 9
  • Thank you very much, your guide helped me a lot but I still have not solved the problem that is converting the json to an array, something like how this page does it: [json-php-array-converter](https://appdevtools.com/json-php-array-converter) – Steve Silva Jan 09 '22 at 06:10
  • Try with `json_decode($json, true)` https://www.php.net/manual/es/function.json-decode.php – Enzo Notario Jan 09 '22 at 13:59