Search code examples
javagraphqlgraphql-java

Return HashMap<String, Object> from GraphQL-Java


I tried few variant and had no luck to return a map in GraphQL. So I have the following two objects:

public class Customer {

    private String name, age;
    // getters & setters
}

public class Person {

   private String type;
   private Map<String, Customer> customers;
   // getters & setters
}

My schema looks like this:

type Customer {
   name: String!
   age:  String!
}

type Person {
  type: String!
  customers: [Customer!] // Here I tried all combination but had no luck, is there a Map type support for GQL?
}

Can someone please tell me how to achieve this so that GraphQL magically process this or an alternative approach.

Many thanks!


Solution

  • Just in case - you can always represent map object as a JSON string (in my case it was helpful).

    public class Person {
    
        private String type;
        private Map<String, Customer> customers;
        // getters & setters
    }
    

    Would be

    type Person {
      type: String!
      customers: String!
    }
    

    After that don't forget to add data fetcher to convert it to the JSON.

    public DataFetcher<String> fetchCustomers() {
            return environment -> {
                Person person = environment.getSource();
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    return objectMapper.writeValueAsString(person.getCustomers());
                } catch (JsonProcessingException e) {
                    log.error("There was a problem fetching the person!");
                    throw new RuntimeException(e);
                }
            };
        }
    

    It'll return:

    "person": {
        "type": "2",
        "customers": "{\"VIP\":{\"name\":\"John\",\"age\":\"19\"},\"Platinum VIP\":{\"name\":\"Peter\",\"age\":\"65\"}}"
      }
    

    After that, you can operate with customers as with typical JSON string in your client.