Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose graphql field with different name

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"   } } 
like image 690
Amit Kumar Avatar asked Dec 19 '17 08:12

Amit Kumar


People also ask

How do you rename a query in GraphQL?

Creating an alias in GraphQL is easy. Simply add a colon and new name next to the field you want to rename.

What are aliases in GraphQL?

What are GraphQL aliases? Aliases allow us to rename the data that is returned in a query's results. Aliases don't change the original schema, instead, they manipulate the structure of the query result that is fetched from your database, displaying it according to your specifications.

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 is the GraphQL type for unique ID?

In Dgraph, every node has a unique 64-bit identifier that you can expose in GraphQL using the ID type. An ID is auto-generated, immutable and never reused. Each type can have at most one ID field.


1 Answers

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   } } 
like image 178
marktani Avatar answered Sep 28 '22 21:09

marktani