Custom map keys in GraphQL response

前端 未结 1 567
鱼传尺愫
鱼传尺愫 2021-01-12 14:56

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, th

相关标签:
1条回答
  • 2021-01-12 15:38

    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!

    0 讨论(0)
提交回复
热议问题