How to expose graphql field with different name

2020-04-02 06:12发布

问题:

I am exploring GraphQL and would like to know if there is any way of renaming the response field for example i have a POJO with these field

class POJO {
  Long id;
  String name;
}

GraphQL query:

type POJO {
  id: Long
  name: String
}

My response is something like this

{
  "POJO" {
    "id": 123,
    "name": "abc"
  }
}

Can i rename the name field to something like userName so that my response is below

{
  "POJO" {
    "id": 123,
    "userName": "abc"
  }
}

回答1:

You can use GraphQL Aliases to modify individual keys in the JSON response.

If this is your original query

query {
  POJO {
    id
    name
  }
}

you can introduce a GraphQL alias userName for the field name like so:

query {
  POJO {
    id
    userName: name
  }
}

You can also use GraphQL aliases to use the same query or mutation field multiple times in the same GraphQL operation. This get's especially interesting when using field parameters:

query {
  first: POJO(first: 1) {
    id
    name
  }

  second: POJO(first: 1, skip: 1) {
    id
    name
  }
}


回答2:

Looks like GraphQLName annotation can help.

Example from documentation : "Additionally, @GraphQLName can be used to override field name. You can use @GraphQLDescription to set a description."

These can also be used for field parameters:

public String field(@GraphQLName("val") String value) {
  return value;
}


回答3:

The question is: how are you creating the schema in the first place? There's no intrinsic connection between Java and GraphQL types - they are completely unrelated unless you correlate them. So you can name the fields any way you want in the schema, and make a resolver (DataFetcher) that gets the value from anywhere (thus any POJO field too).

If you're using a tool to generate the schema from Java types (graphql-java-annotations, graphql-spqr etc), then use that tool's facilities to drive the mapping. Both the mentioned tools allow customizing the mapping via annotations. GraphQL-SPQR enables the same via external configuration as well.

If you clarify your question further, I'll be able to give a more precise answer.