DEV Community

Daniel Bayerlein
Daniel Bayerlein

Posted on

How to add __typename automatically to your GraphQL document

Apollo Client offers the option to automatically adds __typename fields to all outgoing queries.

If you use a minimal GraphQL client like graphql-request, then it is necessary to manually adds __typename fields to all outgoing queries.

After going through the documentation and code of Apollo Client, I became aware of the helper function addTypenameToDocument. This function is responsible to manipulate the GraphQL document by adding __typename automatically. You can use this function with any GraphQL client!

In my case, I wrote a little helper function for graphql-request:

import { addTypenameToDocument } from '@apollo/client/utilities'
import { parse } from 'graphql'
import { GraphQLClient } from 'graphql-request'

const client = new GraphQLClient(endpoint)

export const request = (query, variables, requestHeaders) => {
  // Adds "__typename" to the query
  const document = addTypenameToDocument(
    typeof query === 'string' ? parse(query) : query

  return client.request(document, variables, requestHeaders)
Enter fullscreen mode Exit fullscreen mode

If you have any kind of feedback, suggestions or ideas - feel free to comment this post!

Top comments (0)