Catch the highlights of GraphQLConf 2023! Click for recordings. Or check out our recap blog post.
TypeScript
vue-apollo-smart-ops

TypeScript Vue Apollo Smart Operations

Package nameWeekly DownloadsVersionLicenseUpdated
@graphql-codegen/typescript-vue-apollo-smart-opsDownloadsVersionLicenseNov 26th, 2023

Installation

npm i -D @graphql-codegen/typescript-vue-apollo-smart-ops
⚠️

Usage Requirements In order to use this GraphQL Codegen plugin, please make sure that you have GraphQL operations (query / mutation / subscription and fragment) set as documents: … in your codegen.yml.

Without loading your GraphQL operations (query, mutation, subscription and fragment), you won't see any change in the generated output.

This plugin generates Vue Apollo Smart Query, Smart Subscription and mutation operation functions with TypeScript typings.

This plugin relies on some helper functions and types from the vue-apollo-smart-ops package. That package also adds some optional functionality for improved error handling in Vue Apollo operations which can be configured in the generated code from this plugin.

It extends the basic TypeScript plugins: @graphql-codegen/typescript, @graphql-codegen/typescript-operations - and thus shares a similar configuration.

Config API Reference

withSmartOperationFunctions

type: boolean default: true

Customize the output by enabling/disabling the generated Vue Apollo Smart Operations functions.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         withSmartOperationFunctions: true
       },
     },
   },
 };
 export default config;

vueApolloOperationFunctionsImportFrom

type: string default: vue-apollo-smart-ops

The typescript-vue-apollo-smart-ops plugin requires three functions that are used to define your query, subscription and mutation operation functions:

  • createMutationFunction
  • createSmartQueryOptionsFunction
  • createSmartSubscriptionOptionsFunction

By default, these functions are provided by the vue-apollo-smart-ops package, but you can substitute your own import path if you want to replace them with other implementations.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         vueApolloOperationFunctionsImportFrom: 'vue-apollo-smart-ops'
       },
     },
   },
 };
 export default config;

vueApolloErrorType

type: string default: ApolloError

The operation functions generated by typescript-vue-apollo-smart-ops include some functionality for error handling. This configuration parameter allows you to customise the name of the error type that will be used. The default is to use ApolloError from the apollo-client package.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         vueApolloErrorType: 'ApolloError',
         vueApolloErrorTypeImportFrom: 'apollo-client'
       },
     },
   },
 };
 export default config;

vueApolloErrorTypeImportFrom

type: string default: vue-apollo-smart-ops

The operation functions generated by typescript-vue-apollo-smart-ops include some functionality for error handling. This configuration parameter allows you to customise the package where the error type will be imported from. The default is to use ApolloError from the apollo-client package.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         vueApolloErrorType: 'ApolloError',
         vueApolloErrorTypeImportFrom: 'apollo-client'
       },
     },
   },
 };
 export default config;

vueApolloErrorHandlerFunction

type: string default: undefined

The operation functions generated by typescript-vue-apollo-smart-ops include some functionality for error handling. You may supply an error handler function that will be called when an error occurs in a query, subscription or mutation operation. This function should implement the ApolloOperationErrorHandlerFunction interface from vue-apollo-smart-ops package. You can have a custom handler in your app that shows a notification to the user, for example. If unspecified, this functionality will be disabled and errors handled (or not) by Vue Apollo in the normal way.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         vueApolloErrorHandlerFunction: 'handleApolloError',
         vueApolloErrorHandlerFunctionImportFrom: './src/handleApolloError.ts',
       },
     },
   },
 };
 export default config;

vueApolloErrorHandlerFunctionImportFrom

type: string default: undefined

The import path where vueApolloErrorHandlerFunction should be imported from. Can be a package name or a local file path (anything that works in an import statement).

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         vueApolloErrorHandlerFunction: 'handleApolloError',
         vueApolloErrorHandlerFunctionImportFrom: './src/handleApolloError.ts',
       },
     },
   },
 };
 export default config;

vueAppType

type: string default: undefined

The operation functions generated by typescript-vue-apollo-smart-ops include some functionality for error handling. When an error occurs, the Vue app instance is passed to the error handler. You can customise the expected type of the app object. For example, a Nuxt.js app might use NuxtApp from @nuxt/types/app instead. When unspecified, the default type is Vue from vue/types/vue.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         vueAppType: 'Vue',
         vueAppTypeImportFrom: 'vue/types/vue'
       },
     },
   },
 };
 export default config;

vueAppTypeImportFrom

type: string default: undefined

The import path where vueAppType should be imported from. Can be a package name or a local file path (anything that works in an import statement).

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         vueAppType: 'Vue',
         vueAppTypeImportFrom: 'vue/types/vue'
       },
     },
   },
 };
 export default config;

addDocBlocks

type: boolean default: true

Allows you to enable/disable the generation of docblocks in generated code. Some IDE's (like VSCode) add extra inline information with docblocks, you can disable this feature if your preferred IDE does not.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file.ts': {
       plugins: ['typescript', 'typescript-operations', 'typescript-vue-apollo-smart-ops'],
       config: {
         addDocBlocks: true
       },
     },
   },
 };
 export default config;

noGraphQLTag

type: boolean default: false

Deprecated. Changes the documentMode to documentNode.

gqlImport

type: string default: graphql-tag#gql

Customize from which module will gql be imported from. This is useful if you want to use modules other than graphql-tag, e.g. graphql.macro.

Usage Examples

graphql.macro
codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         gqlImport: 'graphql.macro#gql'
       },
     },
   },
 };
 export default config;
Gatsby
codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         gqlImport: 'gatsby#graphql'
       },
     },
   },
 };
 export default config;

documentNodeImport

type: string default: graphql#DocumentNode

Customize from which module will DocumentNode be imported from. This is useful if you want to use modules other than graphql, e.g. @graphql-typed-document-node.

noExport

type: boolean default: false

Set this configuration to true if you wish to tell codegen to generate code with no export identifier.

dedupeOperationSuffix

type: boolean default: false

Set this configuration to true if you wish to make sure to remove duplicate operation name suffix.

omitOperationSuffix

type: boolean default: false

Set this configuration to true if you wish to disable auto add suffix of operation name, like Query, Mutation, Subscription, Fragment.

operationResultSuffix

type: string default: (empty)

Adds a suffix to generated operation result type names

documentVariablePrefix

type: string default: (empty)

Changes the GraphQL operations variables prefix.

documentVariableSuffix

type: string default: Document

Changes the GraphQL operations variables suffix.

fragmentVariablePrefix

type: string default: (empty)

Changes the GraphQL fragments variables prefix.

fragmentVariableSuffix

type: string default: FragmentDoc

Changes the GraphQL fragments variables suffix.

documentMode

type: DocumentMode default: graphQLTag

Declares how DocumentNode are created:

  • graphQLTag: graphql-tag or other modules (check gqlImport) will be used to generate document nodes. If this is used, document nodes are generated on client side i.e. the module used to generate this will be shipped to the client
  • documentNode: document nodes will be generated as objects when we generate the templates.
  • documentNodeImportFragments: Similar to documentNode except it imports external fragments instead of embedding them.
  • external: document nodes are imported from an external file. To be used with importDocumentNodeExternallyFrom

Note that some plugins (like typescript-graphql-request) also supports string for this parameter.

optimizeDocumentNode

type: boolean default: true

If you are using documentNode: documentMode | documentNodeImportFragments, you can set this to true to apply document optimizations for your GraphQL document. This will remove all "loc" and "description" fields from the compiled document, and will remove all empty arrays (such as directives, arguments and variableDefinitions).

importOperationTypesFrom

type: string default: (empty)

This config is used internally by presets, but you can use it manually to tell codegen to prefix all base types that it's using. This is useful if you wish to generate base types from typescript-operations plugin into a different file, and import it from there.

importDocumentNodeExternallyFrom

type: string default: (empty)

This config should be used if documentMode is external. This has 2 usage:

  • any string: This would be the path to import document nodes from. This can be used if we want to manually create the document nodes e.g. Use graphql-tag in a separate file and export the generated document

  • 'near-operation-file': This is a special mode that is intended to be used with near-operation-file preset to import document nodes from those files. If these files are .graphql files, we make use of webpack loader.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         documentMode: 'external',
         importDocumentNodeExternallyFrom: 'path/to/document-node-file',
       },
     },
   },
 };
 export default config;
codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         documentMode: 'external',
         importDocumentNodeExternallyFrom: 'near-operation-file',
       },
     },
   },
 };
 export default config;

pureMagicComment

type: boolean default: false

This config adds PURE magic comment to the static variables to enforce treeshaking for your bundler.

experimentalFragmentVariables

type: boolean default: false

If set to true, it will enable support for parsing variables on fragments.

strictScalars

type: boolean default: false

Makes scalars strict.

If scalars are found in the schema that are not defined in scalars an error will be thrown during codegen.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         strictScalars: true,
       },
     },
   },
 };
 export default config;

defaultScalarType

type: string default: any

Allows you to override the type that unknown scalars will have.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         defaultScalarType: 'unknown'
       },
     },
   },
 };
 export default config;

scalars

type: ScalarsMap

Extends or overrides the built-in scalars and custom GraphQL scalars to a custom type.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         scalars: {
           DateTime: 'Date',
           JSON: '{ [key: string]: any }',
         }
       },
     },
   },
 };
 export default config;

namingConvention

type: NamingConvention default: change-case-all#pascalCase

Allow you to override the naming convention of the output. You can either override all namings, or specify an object with specific custom naming convention per output. The format of the converter must be a valid module#method. Allowed values for specific output are: typeNames, enumValues. You can also use "keep" to keep all GraphQL names as-is. Additionally, you can set transformUnderscore to true if you want to override the default behavior, which is to preserve underscores.

Available case functions in change-case-all are camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, lowerCase, localeLowerCase, lowerCaseFirst, spongeCase, titleCase, upperCase, localeUpperCase and upperCaseFirst See more

Usage Examples

Override All Names
codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         namingConvention: 'change-case-all#lowerCase',
       },
     },
   },
 };
 export default config;
Upper-case enum values
codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         namingConvention: {
           typeNames: 'change-case-all#pascalCase',
           enumValues: 'change-case-all#upperCase',
         }
       },
     },
   },
 };
 export default config;
Keep names as is
codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
        namingConvention: 'keep',
       },
     },
   },
 };
 export default config;
Remove Underscores
codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         namingConvention: {
           typeNames: 'change-case-all#pascalCase',
           transformUnderscore: true
         }
       },
     },
   },
 };
 export default config;

typesPrefix

type: string default: (empty)

Prefixes all the generated types.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         typesPrefix: 'I',
       },
     },
   },
 };
 export default config;

typesSuffix

type: string default: (empty)

Suffixes all the generated types.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         typesSuffix: 'I',
       },
     },
   },
 };
 export default config;

skipTypename

type: boolean default: false

Does not add __typename to the generated types, unless it was specified in the selection set.

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         skipTypename: true
       },
     },
   },
 };
 export default config;

nonOptionalTypename

type: boolean default: false

Automatically adds __typename field to the generated types, even when they are not specified in the selection set, and makes it non-optional

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         nonOptionalTypename: true
       },
     },
   },
 };
 export default config;

useTypeImports

type: boolean default: false

Will use import type {} rather than import {} when importing only types. This gives compatibility with TypeScript's "importsNotUsedAsValues": "error" option

Usage Examples

codegen.ts
 import type { CodegenConfig } from '@graphql-codegen/cli';
 
 const config: CodegenConfig = {
   // ...
   generates: {
     'path/to/file': {
       // plugins...
       config: {
         useTypeImports: true
       },
     },
   },
 };
 export default config;

dedupeFragments

type: boolean default: false

Removes fragment duplicates for reducing data transfer. It is done by removing sub-fragments imports from fragment definition Instead - all of them are imported to the Operation node.

inlineFragmentTypes

type: string default: inline

Whether fragment types should be inlined into other operations. "inline" is the default behavior and will perform deep inlining fragment types within operation type definitions. "combine" is the previous behavior that uses fragment type references without inlining the types (and might cause issues with deeply nested fragment that uses list types).

emitLegacyCommonJSImports

type: boolean default: true

Emit legacy common js imports. Default it will be true this way it ensure that generated code works with non-compliant bundlers.

Examples

Queries

Using the generated query code.

Basic query

For the given input:

query Messages($type: FeedType!) {
  feed(type: $type) {
    id
  }
}

We can use the generated code like this:

<template>
  <div>
    <div v-if="loading > 0">Loading…</div>
    <ul v-else>
      <li v-for="message in messages">{{ message.id }}</li>
    </ul>
  </div>
</template>
 
<script lang="ts">
import { useMessagesQuery } from '../generated/graphqlOperations'
 
export default {
  apollo: {
    messages: useMessagesQuery({
      // variables will be correctly typed here!
      variables: {
        type: 'HOT'
      },
      loadingKey: 'loading',
      update: data => data.feed
    })
  },
  data() {
    return {
      messages: null,
      loading: 0
    }
  }
}
</script>

Basic mutation

For the given operation:

mutation CreateMessage($text: String!) {
  createMessage(text: $text) {
    id
  }
}

We can use the generated code like this:

<template>
  <div>
    <textarea v-model="text"></textarea>
    <button @click="send">Send Message</button>
  </div>
</template>
 
<script lang="ts">
import { createMessageMutation } from '../generated/graphqlOperations'
 
export default {
  data() {
    return {
      text: ''
    }
  },
  async send() {
    const result = await createMessageMutation(this, {
      variables: {
        text: this.text
      }
    })
 
    if (!result.success || !result.data) {
      alert('Failed to create message')
      return
    }
 
    const messageId = result.data.createMessage.id
  }
}
</script>