How can I reshape a GraphQL response?

Viewed 711

I have a GraphQL query that looks like this:

type Query {
    getProfile(userId: ID!): UserProfile
}

type UserProfile {
    userId: ID!
    name: String!
    email: String!
    street: String!
    city: String
    country: String!
    postal: String!
}

However, it seems like I'm only limited to modifying responses from a query using aliases like this:

query {
    getProfile(userId: "12345") {
        userId
        name
        email
        streetName: street
        city
        country
        postalCode: postal
    }
}

I would like to reshape the response so that I don't have to put the response through a data mapper for my objects. For instance, I might want to reshape the response so that it looks like this:

{
    userId: 12345,
    name: "John",
    email: "john@smith.com",
    address: {
        streetName: "my street name",
        city: "WA",
        country: "US",
        postalCode: "54321"
    }
}

In this case, I have added an extra level of address in the response. Must I have a type declared on the GraphQL server specially for this shape? What if I don't have access to doing that, say, it's a third-party GraphQL API?

It feels like I'm still facing the same issue with having to re-map responses in UI when using a regular REST API. Changing the field names with aliases only is often not enough in my case.

How can I structure my GraphQL query to reshape the response to return in a different shape?

1 Answers

I think you can improve your schema to be something like:

type UserProfile {
    userId: ID!
    name: String!
    email: String!
    address: Address
}

type Address {
    street: String!
    city: String
    country: String!
    postal: String!
}

Then you can have different resolvers for the User data, and the address information if you prefer so

Related