### Development Setup Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Instructions for setting up the development environment for nuxt-graphql-request, including cloning the repository, installing dependencies, and starting the development server. ```bash 1. Clone this repository 2. Install dependencies using `yarn install` or `npm install` 3. Start development server using `yarn dev` or `npm run dev` ``` -------------------------------- ### Install nuxt-graphql-request Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/setup.md Installs the nuxt-graphql-request module for Nuxt 3 using nuxi. For Nuxt 2, it provides the command to install the v6 version along with graphql. ```bash npx nuxi@latest module add graphql-request ``` ```bash yarn add nuxt-graphql-request@v6 graphql --dev ``` -------------------------------- ### Runtime GraphQL Client Configuration Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/setup.md Illustrates how to configure GraphQL client endpoints using Nuxt's runtime config. This allows endpoints to be provided at runtime instead of build time, with examples for default and secondary clients. ```typescript export default defineNuxtConfig({ runtimeConfig: { public: { graphql: { clients: { default: { endpoint: '', }, secondClient: { endpoint: '', }, // ...more clients }, }, }, }, }); ``` -------------------------------- ### Start Development Server Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/README.md Starts the Nuxt.js development server for local testing and development. ```bash yarn dev ``` -------------------------------- ### Preview Static Site Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/README.md Starts a local server to preview the statically generated Nuxt.js application. ```bash yarn start ``` -------------------------------- ### Install Dependencies Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/README.md Installs the necessary project dependencies using Yarn. ```bash yarn install ``` -------------------------------- ### Install Nuxt GraphQL Request Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Installs the nuxt-graphql-request module using the Nuxt CLI. For Nuxt 2, it also installs graphql as a dev dependency. ```bash npx nuxi@latest module add graphql-request ``` ```bash yarn add nuxt-graphql-request@v6 graphql --dev ``` -------------------------------- ### AbortController Polyfill for Node.js v12 Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/cancellation.md This snippet demonstrates how to use the 'abort-controller' polyfill for Node.js environments older than v14.17.0, where AbortController is not natively supported. It imports the polyfill and then creates an instance of AbortController. ```ts import 'abort-controller/polyfill'; const abortController = new AbortController(); ``` -------------------------------- ### TypeScript Configuration Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/setup.md Provides the necessary tsconfig.json configuration to ensure TypeScript type definitions work correctly with Nuxt.js projects, extending the auto-generated Nuxt config. ```json { "extends": "./.nuxt/tsconfig.json" } ``` -------------------------------- ### Nuxt.js GraphQL Client Configuration Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/setup.md Demonstrates how to configure GraphQL clients within the nuxt.config.ts file. It shows setting up multiple clients, specifying endpoints, and overriding default fetch options. It also includes options for including node_modules and setting the default HTTP method. ```typescript export default defineNuxtConfig({ modules: ['nuxt-graphql-request'], graphql: { /** * An Object of your GraphQL clients */ clients: { default: { /** * The client endpoint url */ endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', /** * Per-client options overrides * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: {}, }, secondClient: { // ...client config }, // ...your other clients }, /** * Options * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: { method: 'get', // Default to `POST` }, /** * Optional * default: false (this includes graphql-tag for node_modules folder) */ includeNodeModules: true, }, }); ``` -------------------------------- ### Request and Response Middleware Example Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/middleware.md This example shows how to define and use request and response middleware functions. The request middleware adds an authentication token to the request headers, while the response middleware logs errors along with a trace ID if present in the response headers. ```ts function requestMiddleware(request: RequestInit) { const token = getToken(); return { ...request, headers: { ...request.headers, 'x-auth-token': token }, }; } function responseMiddleware(response: Response) { if (response.errors) { const traceId = response.headers.get('x-b3-traceid') || 'unknown'; console.error( `[${traceId}] Request error: status ${response.status} details: ${response.errors}` ); } } ``` -------------------------------- ### Vue GraphQL Mutation Example Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/error-handling.md Demonstrates how to define and execute a GraphQL mutation in a Vue.js component using nuxt-graphql-request. It shows the import of gql utility, accessing the graphql client, defining the mutation string, setting variables, and making the request. ```vue ``` -------------------------------- ### Perform GraphQL Mutations Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Demonstrates how to execute GraphQL mutations to modify data on the server. The example shows a mutation for inserting a movie, including defining the mutation string and passing variables. ```vue ``` -------------------------------- ### GraphQL Request with Error Handling Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/graphql-mutations.md Demonstrates making a GraphQL request and catching potential errors. It uses the `gql` utility for query construction and `useNuxtApp` to access the GraphQL client. The example includes a `try...catch` block to log errors to the console and exit the process if an error occurs. ```vue ``` -------------------------------- ### Batch GraphQL Queries Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Demonstrates how to send multiple GraphQL queries in a single request using the batchRequests method. This is useful for optimizing network requests by fetching related data simultaneously. It includes examples of defining queries and their corresponding variables. ```vue ``` -------------------------------- ### Handle GraphQL Errors Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Provides an example of how to handle potential errors during GraphQL requests using a try-catch block. The `request()` method can throw errors, which can be caught and logged or processed as needed. ```vue ``` -------------------------------- ### Cancel GraphQL Request with AbortController Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/cancellation.md This snippet shows how to cancel a GraphQL request using an AbortController's signal. It imports necessary modules, defines a GraphQL query, creates an AbortController, and passes its signal to the request. Finally, it aborts the controller to cancel the request. ```vue ``` -------------------------------- ### Receive Raw GraphQL Response Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Explains how to use the `rawRequest()` method to get the complete GraphQL response, including `data`, `errors`, `extensions`, `headers`, and `status`. This is useful when you need access to metadata beyond just the data payload. ```ts import { gql } from 'nuxt-graphql-request/utils'; const { $graphql } = useNuxtApp(); const query = gql` query planets($first: Int) { allPlanets(first: $first) { planets { id name } } } `; const variables = { first: 10 }; const { data, errors, extensions, headers, status } = await $graphql.default.rawRequest( endpoint, query, variables ); console.log(JSON.stringify({ data, errors, extensions, headers, status }, undefined, 2)); ``` -------------------------------- ### Fetch All Planets with Pinia and GraphQL Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/usage/store.md Demonstrates how to define a Pinia store with an action to fetch all planets using a GraphQL query. It utilizes `defineStore` from Pinia and `gql` from `nuxt-graphql-request/utils`. The action `fetchAllPlanets` executes a GraphQL query and updates the store's state with the fetched planet data. ```ts import { defineStore } from 'pinia'; import { gql } from 'nuxt-graphql-request/utils'; import { useNuxtApp } from '#imports'; type Planet = { id: number; name: string }; export const useMainStore = defineStore('main', { state: () => ({ planets: null as Planet[] | null, }), actions: { async fetchAllPlanets() { const query = gql` query planets { allPlanets { planets { id name } } } `; const data = await useNuxtApp().$graphql.default.request(query); this.planets = data.allPlanets.planets; }, }, }); ``` ```graphql query planets { allPlanets { planets { id name } } } ``` -------------------------------- ### Generate Static Site Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/README.md Generates the static version of the Nuxt.js application, creating a `dist/` directory for deployment. ```bash yarn generate ``` -------------------------------- ### Store Actions for GraphQL Data Fetching with Pinia Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Illustrates how to integrate GraphQL data fetching into Pinia store actions, allowing for centralized state management and data retrieval. ```javascript import { defineStore } from 'pinia'; import { gql } from 'nuxt-graphql-request/utils'; import { useNuxtApp } from '#imports'; type Planet = { id: number; name: string }; export const useMainStore = defineStore('main', { state: () => ({ planets: null as Planet[] | null, }), actions: { async fetchAllPlanets() { const query = gql` query planets { allPlanets { planets { id name } } } `; const data = await useNuxtApp().$graphql.default.request(query); this.planets = data.allPlanets.planets; }, }, }); ``` -------------------------------- ### Set Headers Dynamically Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/passing-more-options-to-fetch.md Demonstrates how to dynamically set or override headers for the GraphQL client using `setHeader` or `setHeaders` methods after the Nuxt app has been initialized. ```ts const { $graphql } = useNuxtApp(); // Set a single header $graphql.default.setHeader('credentials', 'include'); $graphql.default.setHeader('mode', 'cors'); // Override all existing headers $graphql.default.setHeaders({ credentials: 'include', mode: 'cors', }); ``` -------------------------------- ### Nuxt Configuration for GraphQL Clients Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Configures GraphQL clients within the nuxt.config.js file, specifying endpoints and options for each client. Includes options for build-time and runtime configuration. ```ts module.exports = { modules: ['nuxt-graphql-request'], build: { transpile: ['nuxt-graphql-request'], }, graphql: { /** * An Object of your GraphQL clients */ clients: { default: { /** * The client endpoint url */ endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', /** * Per-client options overrides * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: {}, }, secondClient: { // ...client config }, // ...your other clients }, /** * Options * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: { method: 'get', // Default to `POST` }, /** * Optional * default: false (this includes graphql-tag for node_modules folder) */ includeNodeModules: true, }, }; ``` ```ts module.exports = { publicRuntimeConfig: { graphql: { clients: { default: { endpoint: '', }, secondClient: { endpoint: '', }, // ...more clients }, }, }, }; ``` -------------------------------- ### Configure GraphQL Client Options Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/passing-more-options-to-fetch.md This snippet shows how to configure the default GraphQL client in nuxt.config.ts to include specific fetch options like credentials and CORS mode. ```ts export default defineNuxtConfig({ graphql: { clients: { default: { endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', options: { credentials: 'include', mode: 'cors', }, }, }, }, }); ``` -------------------------------- ### GraphQL Document Usage Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Explains that wrapping GraphQL documents with the `gql` template from `graphql-request` is optional and primarily for tooling support like formatting and syntax highlighting. Alternatively, `gql` from `graphql-tag` can be used. ```javascript // Optional: Wrap your GraphQL documents for tooling support // import { gql } from 'graphql-request'; // const query = gql`...`; // Or use graphql-tag if needed // import { gql } from 'graphql-tag'; // const query = gql`...`; ``` -------------------------------- ### TypeScript Configuration Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Sets up TypeScript configuration by extending Nuxt's auto-generated tsconfig.json for seamless integration. ```json { "extends": "./.nuxt/tsconfig.json" } ``` -------------------------------- ### Incrementally Set Headers for GraphQL Client Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/authentication.md Demonstrates how to dynamically update or set headers for an existing GraphQL client instance after initialization. It covers both setting all headers at once with `setHeaders` and updating a single header with `setHeader`. ```javascript const { $graphql } = useNuxtApp(); // Override all existing headers $graphql.default.setHeaders({ authorization: 'Bearer MY_TOKEN' }); // Set a single header $graphql.default.setHeader('authorization', 'Bearer MY_TOKEN'); ``` -------------------------------- ### Dynamically Set Headers for GraphQL Client Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Demonstrates how to set or override headers for an existing GraphQL client instance after initialization using `setHeader()` for a single header or `setHeaders()` for multiple headers. This allows for dynamic header management based on application state or user actions. ```ts const { $graphql } = useNuxtApp(); // Override all existing headers $graphql.default.setHeaders({ authorization: 'Bearer MY_TOKEN' }); // Set a single header $graphql.default.setHeader('authorization', 'Bearer MY_TOKEN'); ``` -------------------------------- ### Execute Batch GraphQL Queries Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/batch-queries.md This snippet shows how to send multiple GraphQL queries in a single batch request. It defines three separate queries with their respective variables and then uses the `$graphql.default.batchRequests` method to execute them concurrently. The results are logged to the console, and errors are caught and logged. ```vue ``` -------------------------------- ### Dynamically Set Fetch Options Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Demonstrates how to set or override fetch options like `credentials` or `mode` dynamically after the GraphQL client has been initialized, using `setHeader()` or `setHeaders()`. ```ts const { $graphql } = useNuxtApp(); // Set a single header $graphql.default.setHeader('credentials', 'include'); $graphql.default.setHeader('mode', 'cors'); // Override all existing headers $graphql.default.setHeaders({ credentials: 'include', mode: 'cors', }); ``` -------------------------------- ### Nuxt Configuration with GraphQL Request Module Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/middleware.md This snippet demonstrates how to configure the nuxt-graphql-request module in your Nuxt.js application. It includes setting up a default GraphQL client with custom request and response middleware, as well as global options for the module. ```javascript export default defineNuxtConfig({ modules: ['nuxt-graphql-request'], graphql: { /** * An Object of your GraphQL clients */ clients: { default: { /** * The client endpoint url */ endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', /** * Per-client options overrides * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: { requestMiddleware: requestMiddleware, responseMiddleware: responseMiddleware, }, }, // ...your other clients }, /** * Options * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: { method: 'get', // Default to `POST` }, /** * Optional * default: false (this includes graphql-tag for node_modules folder) */ includeNodeModules: true, }, }); // Assuming requestMiddleware and responseMiddleware are defined elsewhere in the scope ``` -------------------------------- ### Usage with useAsyncData in Nuxt Components Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Demonstrates how to use the $graphql client with Nuxt's useAsyncData composable to fetch data asynchronously in Vue components. ```vue ``` -------------------------------- ### Nuxt GraphQL Request Configuration with Middleware Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Illustrates how to configure nuxt-graphql-request within the Nuxt.js application. This includes setting up client endpoints, defining request and response middleware for tasks like adding authentication headers or logging errors, and configuring global options. ```ts function requestMiddleware(request: RequestInit) { const token = getToken(); return { ...request, headers: { ...request.headers, 'x-auth-token': token }, }; } function responseMiddleware(response: Response) { if (response.errors) { const traceId = response.headers.get('x-b3-traceid') || 'unknown'; console.error( `[${traceId}] Request error: status ${response.status} details: ${response.errors}` ); } } export default defineNuxtConfig({ modules: ['nuxt-graphql-request'], graphql: { /** * An Object of your GraphQL clients */ clients: { default: { /** * The client endpoint url */ endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', /** * Per-client options overrides * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: { requestMiddleware: requestMiddleware, responseMiddleware: responseMiddleware, }, }, // ...your other clients }, /** * Options * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch */ options: { method: 'get', // Default to `POST` }, /** * Optional * default: false (this includes graphql-tag for node_modules folder) */ includeNodeModules: true, }, }); ``` -------------------------------- ### Fetch data with useAsyncData Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/usage/components.md Demonstrates fetching data from a GraphQL API using the `useAsyncData` composable in Nuxt.js. It defines a GraphQL query and uses the `$graphql` instance to make the request, returning the fetched planet data. ```vue ``` -------------------------------- ### Fetch Data with GraphQL Variables in Vue Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/using-graphql-document-variables.md This snippet shows how to define a GraphQL query with variables and pass those variables to the request. It utilizes the `gql` utility from `nuxt-graphql-request/utils` and the `$graphql` instance from `useNuxtApp`. ```vue ``` -------------------------------- ### User-defined Functions for Data Fetching Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Shows how to define custom functions within a Nuxt component to fetch GraphQL data using the $graphql client and update local state. ```vue ``` -------------------------------- ### Pass Fetch Options in nuxt.config.ts Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Configures additional options for the underlying `fetch` API within the GraphQL client in `nuxt.config.ts`. This allows customization of network requests, such as setting `credentials` or `mode`. ```ts export default defineNuxtConfig({ graphql: { clients: { default: { endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', options: { credentials: 'include', mode: 'cors', }, }, }, }, }); ``` -------------------------------- ### Accessing Raw GraphQL Response Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/receiving-a-raw-response.md Demonstrates how to use the `rawRequest` method to obtain the full GraphQL response object, which includes `data`, `errors`, `extensions`, `headers`, and `status`. This is useful when you need to inspect parts of the response beyond just the data or errors. ```ts import { gql } from 'nuxt-graphql-request/utils'; const { $graphql } = useNuxtApp(); const query = gql` query planets($first: Int) { allPlanets(first: $first) { planets { id name } } } `; const variables = { first: 10 }; const { data, errors, extensions, headers, status } = await $graphql.default.rawRequest( endpoint, query, variables ); console.log(JSON.stringify({ data, errors, extensions, headers, status }, undefined, 2)); ``` -------------------------------- ### Request Cancellation with AbortController Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Shows how to cancel an ongoing GraphQL request using the AbortController API. This is crucial for improving user experience by preventing unnecessary network activity when a component unmounts or a user navigates away. It also mentions polyfill availability for older Node.js versions. ```vue import { gql } from 'nuxt-graphql-request/utils'; const { $graphql } = useNuxtApp(); const fetchSomething = async () => { const query = gql` query planets { allPlanets { planets { id name } } } `; const abortController = new AbortController(); const planets = await $graphql.default.request({ document: query, signal: abortController.signal, }); abortController.abort(); }; ``` ```ts import 'abort-controller/polyfill'; const abortController = new AbortController(); ``` -------------------------------- ### Fetch data with user-defined function Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/usage/components.md Illustrates fetching GraphQL data within a user-defined function in a Nuxt.js component. It shows how to define a query, use the `$graphql` instance to make the request, and update a ref with the fetched planet data. ```vue ``` -------------------------------- ### Use GraphQL Document Variables Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Shows how to pass variables to a GraphQL query defined using the `gql` tag. Variables are passed as the second argument to the `request()` method, allowing for dynamic query parameters. ```vue ``` -------------------------------- ### Configure Authentication Header in nuxt.config.ts Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Sets the default authorization header for all GraphQL requests by configuring the `graphql` client in `nuxt.config.ts`. This is useful for projects requiring authentication via bearer tokens or other header-based methods. ```ts export default defineNuxtConfig({ graphql: { clients: { default: { endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', options: { headers: { authorization: 'Bearer MY_TOKEN', }, }, }, }, }, }); ``` -------------------------------- ### Configure Authentication Headers in nuxt.config.ts Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/authentication.md This snippet shows how to set the `authorization` header globally for all GraphQL requests within the Nuxt application by configuring the `graphql` module in `nuxt.config.ts`. It targets the default GraphQL client. ```ts export default defineNuxtConfig({ graphql: { clients: { default: { endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index', options: { headers: { authorization: 'Bearer MY_TOKEN', }, }, }, }, }, }); ``` -------------------------------- ### Dynamically Set GraphQL Endpoint Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Shows how to change the GraphQL endpoint of a client instance after it has been initialized using the `setEndpoint()` function. This is useful for scenarios where the GraphQL API endpoint might change during the application's lifecycle. ```ts const { $graphql } = useNuxtApp(); $graphql.default.setEndpoint(newEndpoint); ``` -------------------------------- ### Set GraphQL Endpoint Dynamically Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/authentication.md Illustrates how to change the GraphQL endpoint of a client instance after it has been initialized. This is useful for scenarios where the endpoint might change during the application's lifecycle. ```javascript const { $graphql } = useNuxtApp(); $graphql.default.setEndpoint(newEndpoint); ``` -------------------------------- ### Pass Custom Headers in Each GraphQL Request Source: https://github.com/gomah/nuxt-graphql-request/blob/master/README.md Illustrates how to pass custom headers for individual GraphQL requests using the `request()` or `rawRequest()` methods. The headers are provided as the third parameter to these methods, overriding any default headers configured for the client. ```vue ``` -------------------------------- ### Pass Custom Headers in Each GraphQL Request Source: https://github.com/gomah/nuxt-graphql-request/blob/master/docs/content/en/examples/authentication.md Shows how to include custom headers, such as an authorization token, directly within individual GraphQL requests. This method overrides any globally or incrementally set headers for that specific request. ```vue ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.