Andreas
Andreas

Reputation: 53

Flatten Apollo GraphQL Response (Data Field)

A Client needs a specific JSON structure which I wanted to provide by an GraphQL Response.

Unfortunately I have to get rid of the top level "data" field and flatten the response for that client.

Is there a way to do this by a resolver?

From:

{ 
   "data" : {
      "myKey": 
         {...}
   }
}

To:

{ 
   "myKey": 
      {...}
}

Thanks!

Upvotes: 1

Views: 2130

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84727

It's technically possible by utilizing the formatResponse option passed in to ApolloServer's constructor:

const formatResponse = ({ data, errors }) => data
const server = new ApolloServer({ typeDefs, resolvers, formatResponse })

or to do that for a specific query (for example, status), you can do:

    const formatResponse = res => {
      if (res.data && res.data.status) return res.data
      return res
    }

However, I would highly advise against this sort of approach for two main reasons. One, it breaks the spec, which is going to make your API incompatible with most client libraries out there designed for explicitly working with GraphQL APIs. Two, it leaves you with either having to inject your errors (validation or otherwise) into your actual data somewhere, or leaving them out altogether.

It's hard to imagine a scenario where pulling the data out of the response shouldn't be done by the client application -- and if you're having a hard time with that on a particular framework, that sounds like a good follow up SO question!

Upvotes: 3

Related Questions