nuxt-graphql-client

repository·main·Indexed 19 days ago

https://github.com/diizzayy/nuxt-graphql-client

A minimal GraphQL client and code generation tool optimized for Nuxt 3. It provides full TypeScript support, Hot Module Reload (HMR) for GraphQL documents, and leverages graphql-request and graphql-code-generator. Key features include zero configuration, automatically generated Gql functions, and composables such as useAsyncGql, useGql, and useGqlToken for managing requests, authorization, and error handling.

Tokens
12.8K
Snippets
41
Records
51
Agent score
61%

What's inside nuxt-graphql-client

  1. Overview of nuxt-graphql-client

    main
    nuxt-graphql-client is a minimal GraphQL client designed for Nuxt 3 that includes built-in code generation. It provides a seamless developer experience with full TypeScript support and Hot Module Reload (HMR) for GraphQL documents, meaning changes to your queries are reflected immediately without manual regeneration steps.
  2. How to associate GraphQL operations with specific clients

    main

    When using Multiple Client Mode, you must tell the module which client an operation belongs to. You can do this using one of three methods, listed in order of precedence:

    1. File Suffix (Highest Precedence): Name your GraphQL file with the client name as a suffix before the extension: <clientname>.gql or <clientname>.graphql. For example, example.github.gql will be linked to the github client.
    2. Directory Name: Place your GraphQL files inside a folder named after the client. For example, files in ./queries/spacex/ will be linked to the spacex client.
    3. Default Fallback (Lowest Precedence): If neither of the above methods is used, the operation is automatically linked to the default client.
  3. How to chain multiple GraphQL operations in Nuxt

    main

    Due to how Nuxt 3 handles SSR, the Nuxt instance context is lost after the first await statement. This means you cannot call multiple Gql Functions sequentially if they rely on the Nuxt context (like useState or useRoute) inside an async function.

    The Problem (Invalid Approach)

    Calling a second Gql Function after an await will fail because the context is gone.

    export const useExample = async () => {
      const { user } = await GqlUser() // Context lost here
      const { relations } = await GqlRelations({ id: user.id }) // Fails
    }

    Use the useGql composable to create a single instance. This allows you to perform multiple queries/mutations while maintaining the necessary context. Additionally, ensure any Nuxt composables (like useState) are called before the first await statement.

    export const useExample = async () => {
      const GqlInstance = useGql()
    
      // Access Nuxt composables BEFORE the first await
      const myState = useState('example')
    
      const { user } = await GqlInstance('user')
      const { relations } = await GqlInstance('relations', { id: user.id })
    
      // myState is still accessible
    }
    export const useExample = async () => {
      const GqlInstance = useGql()
      const myState = useState('example')
    
      const { user } = await GqlInstance('user')
      const { relations } = await GqlInstance('relations', { id: user.id })
    }
  4. Key features of nuxt-graphql-client

    main

    The module provides the following core capabilities:

    • Zero Configuration: Works out of the box with minimal setup.
    • Nuxt 3 Support: Built specifically for the Nuxt 3 ecosystem.
    • Full TypeScript Support: Provides type safety for your GraphQL queries.
    • HMR for GraphQL documents: Automatically updates types and client state when GraphQL documents change.
    • Minimalist Core: Leverages graphql-request for the client and graphql-code-generator for code generation.
  5. Generate types from a local schema file

    main

    If your GraphQL API is not publicly available or you prefer not to use introspection over the network, you can provide a path to a local schema file. The module will use this file to generate types for your GraphQL operations. Provide the path relative to your project root in the schema property within your client configuration.

    export default defineNuxtConfig({
      modules: ['nuxt-graphql-client'],
    
      runtimeConfig: {
        public: {
          'graphql-client': {
            clients: {
              default: {
                schema: '<relative_path_to_schema_file>',
              }
            }
          }
        }
      }
    })
  6. Write and generate GraphQL operations

    main

    Operations (queries and mutations) must be written in .gql or .graphql files. Writing operations directly within SFC components is not supported.

    nuxt-graphql-client automatically parses these files and generates corresponding functions and types. The generated function name is derived from the GraphQL operation name.

    Example Operation: Create a file at ./queries/starlink.gql:

    query launches($limit: Int = 5) {
      launches(limit: $limit) {
        id
        launch_year
        mission_name
      }
    }

    This will generate a function named GqlLaunches() (based on the operation name launches) that is fully typed based on the GraphQL document. To trigger code generation, run your development server (e.g., yarn dev).

  7. Configure multiple GraphQL clients

    main

    To interact with multiple GraphQL APIs, add a clients key to the graphql-client property within your Nuxt runtimeConfig.public. Each key in the clients object represents a unique client name.

    If you configure more than one client, the module enters Multiple Client Mode. In this mode, you must explicitly associate GraphQL operations with a specific client using file naming or directory structures, otherwise, they will fall back to the default client.

    import { defineNuxtConfig } from 'nuxt'
    
    export default defineNuxtConfig({
      modules: ['nuxt-graphql-client'],
    
      runtimeConfig: {
        public: {
          'graphql-client': {
            clients: {
              default: 'https://spacex-production.up.railway.app/',
              github: {
                host: 'https://api.github.com/graphql',
                token: 'your_access_token',
              },
              countries: {
                host: 'https://countries.trevorblades.com/graphql',
                token: {
                  name: 'X-Custom-Auth',
                  value: 'your_access_token'
                }
              }
            }
          }
        }
      }
    })
  8. Install and setup nuxt-graphql-client

    main

    To use nuxt-graphql-client in a Nuxt 3 application, follow these steps:

    1. Install the module using the Nuxt CLI:

      npx nuxi@latest module add graphql-client
    2. Enable the module in your nuxt.config.ts:

      import { defineNuxtConfig } from 'nuxt/config'
      
      export default defineNuxtConfig({
        modules: ['nuxt-graphql-client'],
      })
    3. Configure the GraphQL API URL by providing a GQL_HOST. You can define this in nuxt.config.ts or via a .env file. Note that a GQL_HOST value in .env will overwrite the value defined in runtimeConfig.

    Using nuxt.config.ts:

    export default defineNuxtConfig({
      modules: ['nuxt-graphql-client'],
      runtimeConfig: {
        public: {
          GQL_HOST: 'https://your-api-url.com/'
        }
      }
    })

    Using .env:

    GQL_HOST="https://your-api-url.com/"
    npx nuxi@latest module add graphql-client
  9. Use automatically generated Gql Functions

    main

    Gql Functions are automatically generated and imported based on the GraphQL operations defined in your project. They allow you to execute queries and mutations as simple asynchronous functions.

    Naming Convention

    Functions are named using the pattern Gql + [OperationName]. For example, a query named GetUsers becomes the function GqlGetUsers().

    Requirements

    • Operation Names: Every GraphQL operation must have a name. Anonymous operations (e.g., query { ... }) are skipped and will not generate a Gql Function.
    • File Location: Operations must be written in .gql or .graphql files located anywhere in your project.
    • No SFC Writing: Writing GraphQL operations directly inside Single File Components (SFCs) is not supported.
    query GetUsers {
      users {
        id
        name
      }
    }
    
    mutation LoginUser($email: String!, $password: String!) {
      login(email: $email, password: $password) {
        id
        name
      }
    }
    // Generated functions are automatically imported
    async function loadUsers() {
      const result = await GqlGetUsers()
    }
    
    async function handleLogin(email: string, password: string) {
      const result = await GqlLoginUser(email, password)
    }