Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom map keys in GraphQL response

I've been looking into GraphQL as a replacement for some REST APIs of mine, and while I think I've wrapped my head around the basics and like most of what I see so far, there's one important feature that seems to be missing.

Let's say I've got a collection of items like this:

{
    "id": "aaa",
    "name": "Item 1",
    ...
}

An application needs a map of all those objects, indexed by ID as such:

{
    "allItems": {
        "aaa": {
            "name": "Item 1",
            ...
        },
        "aab": {
            "name": "Item 2",
            ...
        }
    }
}

Every API I've ever written has been able to give results back in a format like this, but I'm struggling to find a way to do it with GraphQL. I keep running across issue 101, but that deals more with unknown schemas. In my case, I know exactly what all the fields are; this is purely about output format. I know I could simply return all the items in an array and reformat it client-side, but that seems like overkill given that it's never been needed in the past, and would make GraphQL feel like a step backwards. I'm not sure if what I'm trying to do is impossible, or I'm just using all the wrong terminology. Should I keep digging, or is GraphQL just not suited to my needs? If this is possible, what might a query look like to retrieve data like this?

I'm currently working with graphql-php on the server, but I'm open to higher-level conceptual responses.

like image 386
Dan Hlavenka Avatar asked Jan 09 '17 21:01

Dan Hlavenka


People also ask

How do I return a map in GraphQL?

In order to return a Map, we've got three options: Return as JSON String. Use GraphQL custom scalar type. Return as List of key-value pairs.

What is __ Typename in GraphQL?

The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).

What are the 2 most common actions in GraphQL?

From the point of view of the client, the most common GraphQL operations are likely to be queries and mutations.

Is GraphQL strong typing?

Strongly-typed: GraphQL is strongly-typed. Given a query, tooling can ensure that the query is both syntactically correct and valid within the GraphQL type system before execution, i.e. at development time, and the server can make certain guarantees about the shape and nature of the response.


1 Answers

Unfortunately returning objects with arbitrary and dynamic keys like this is not really a first-class citizen in GraphQL. That is not to say you can't achieve the same thing, but in doing so you will lose many of the benefits of GraphQL.

If you are set on returning an object with id keys instead of returning a collection/list of objects containing the ids and then doing the transformation on the client then you can create a special GraphQLScalarType.

const GraphQLAnyObject = new GraphQLScalarType({
  name: 'AnyObject',
  description: 'Any JSON object. This type bypasses type checking.',
  serialize: value => {
    return value;
  },
  parseValue: value => {
    return value;
  },
  parseLiteral: ast => {
    if (ast.kind !== Kind.OBJECT) {
      throw new GraphQLError("Query error: Can only parse object but got a: " + ast.kind, [ast]);
    }
    return ast.value;
  }
});

The problem with this approach is that since it is a scalar type you cannot supply a selection set to query it. E.G. if you had a type

type MyType implements Node {
  id: ID!
  myKeyedCollection: AnyObject
}

Then you would only be able to query it like so

query {
  getMyType(id: abc) {
    myKeyedCollection  # note there is no { ... }
  }
}

As others have said, I wouldn't recommend this because you are losing a lot of the benefits of GraphQL but it goes to show that GraphQL can still do pretty much anything REST can.

Hope this helps!

like image 164
mparis Avatar answered Oct 12 '22 05:10

mparis