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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay