Skip to content

Modifying Response of Graphql before sent out

I am looking for a way to modify the response object of a graphql query or mutation before it gets sent out.

Basically in addition the the data object, I want to have extra fields like code and message.

At the moment I am solving this by adding the fields directly into my GQL schemas take this type definition for example:

type Query {
  myItems: myItemResponse
}

type myItemResponse {
  myItem: Item
  code: String!
  success: Boolean!
  message: String!
}

The response itself would be look like that:

{
   data: {
      myItems: {
         myItem: [ ... fancy Items ... ],
         message: 'successfully retrieved fancy Items',
         code: <CODE_FOR_SUCCESSFUL_QUERY>
      }
   }
}

I find that solution not nice because it overcomplicates things in my FrontEnd.

I would prefer a solution where message code and other Metadata are seperated from the actual data, so something like this:

{
   data: {
      myItems: [ ... fancy Items ... ],
   },
   message: 'successfully retrieved fancy Items',
   code: <CODE_FOR_SUCCESSFUL_QUERY>
}

With apollo-server I already tried the formatResponse object in the constructor:

const server = new ApolloServer({
   ...
   formatResponse({ data }) {
     return {
        data,
        test: 'Property to test if shown in the FrontEnd',
     }
   }
   ...
}

unfortunately that doesn’t have the desired effect. Before I use express middlewares I want to ask if there is a possibility to do this via apollo-server out of the box or if I am maybe just missing something in the formatResponse function.

Answer

from graphql.org: A response to a GraphQL operation must be a map.

If the operation encountered any errors, the response map must contain an entry with key errors. The value of this entry is described in the “Errors” section. If the operation completed without encountering any errors, this entry must not be present.

If the operation included execution, the response map must contain an entry with key data. The value of this entry is described in the “Data” section. If the operation failed before execution, due to a syntax error, missing information, or validation error, this entry must not be present.

The response map may also contain an entry with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.

To ensure future changes to the protocol do not break existing servers and clients, the top level response map must not contain any entries other than the three described above.