• Plugins
  • TypeScript
  • named-operations-object

Named Operations Object

Package nameWeekly DownloadsVersionLicenseUpdated
@graphql-codegen/named-operations-objectDownloadsVersionLicenseAug 8th, 2022

Installation

yarn add -D @graphql-codegen/named-operations-object

This plugin generates an object containing a list of all your GraphQL operations and fragments. This is useful if you are using Apollo-Client and wish to have type validation when you are using refetchQueries.

All operations and fragments are being exported by their name (so unnamed operations are being ignored), in the following structure:

export const namedOperations = {
  Query: [...],
  Mutation: [...],
  Subscription: [...],
  Fragment: [...]
}

Config API Reference

identifierName

type: string default: namedOperations

Allow you to customize the name of the exported identifier

Usage Examples

generates:
  path/to/file.ts:
    plugins:
      - typescript
      - named-operations-object
    config:
      identifierName: ListAllOperations
useConsts

type: boolean default: false

Will generate a const string instead of regular string.

How to use?

Include the plugin within your output (into an existing .js/.ts file, or a new file), for example:

codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli'
 
const config: CodegenConfig = {
  schema: 'YOUR_SCHEMA',
  documents: 'YOUR_OPERATIONS',
  generates: {
    './types.ts': {
      plugins: ['typescript', 'typescript-operations', 'named-operations-object']
    }
  }
}
export default config

Refetch queries without input parameters

From this point, you should be able to import namedOperations from that file, and use the names within your code. For example, with Apollo Client and a refetch query that has no input parameters, you can simply add the named operation to the refetchQueries array:

client
  .mutate(
    { ... },
    // No more typos, and you get auto-completion and build time validation
    { refetchQueries: [namedOperations.Query.myQuery] }
  )

Refetch queries with input parameters

For refetch queries that contain input parameters, instead of adding a named operation to the refetchQueries array, you need to add an Apollo QueryOptions object. The query value inside the QueryOptions object does not take one of the entries in the namedOperations list. Instead, the query value takes a TypedDocument constant which corresponds to your query and should be generated by default.

A refetchQueries array that contains multiple queries, some of which contain input parameters, might look something like this:

client
  .mutate(
    { ... },
    // No more typos, and you get auto-completion and build time validation
    { refetchQueries: [
      namedOperations.Query.myQueryWithoutInputParams,
      {
        query: MyQueryWithInputParamsDocument,
        variables: { inputParam }
      }
    ] }
  )
Last updated on October 13, 2022