### Quickstart GraphQL Request Source: https://github.com/onfido/graphql-request/blob/main/README.md Send a GraphQL query with a single line of code using the request function and gql template literal. This example assumes a global fetch is available. ```js import { request, gql } from 'graphql-request' const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` request('https://api.graph.cool/simple/v1/movies', query).then((data) => console.log(data)) ``` -------------------------------- ### Install graphql-request and graphql Source: https://github.com/onfido/graphql-request/blob/main/README.md Install the graphql-request library and its peer dependency graphql using npm. ```sh npm add graphql-request graphql ``` -------------------------------- ### File Upload Example (Browser) Source: https://github.com/onfido/graphql-request/blob/main/README.md Provides an example of how to perform a file upload using graphql-request in a browser environment. This involves constructing a FormData object. ```js import { GraphQLClient } from 'graphql-request' const endpoint = 'YOUR_ENDPOINT' const client = new GraphQLClient(endpoint) const fileInput = document.querySelector('input[type="file"]') const query = ` mutation uploadFile($file: Upload!) { uploadFile(file: $file) } ` fileInput.addEventListener('change', event => { const file = event.target.files[0] const variables = { file, } client.request(query, variables).then(data => console.log(data)) }) ``` -------------------------------- ### Using a Custom `fetch` Method with Cookie Support Source: https://github.com/onfido/graphql-request/blob/main/README.md Demonstrates how to integrate a custom `fetch` method, specifically one with cookie support from `fetch-cookie`, into `graphql-request`. This example uses `cross-fetch` for browser compatibility. Ensure `fetch-cookie` and `cross-fetch` are installed. ```javascript import { GraphQLClient, gql } from 'graphql-request' import crossFetch from 'cross-fetch' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' // a cookie jar scoped to the client object const fetch = require('fetch-cookie')(crossFetch) const graphQLClient = new GraphQLClient(endpoint, { fetch }) const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` const data = await graphQLClient.rawRequest(query) console.log(JSON.stringify(data, undefined, 2)) } ``` -------------------------------- ### Install `fetch-cookie` for Node.js Source: https://github.com/onfido/graphql-request/blob/main/README.md Installs the `fetch-cookie` package, which is necessary for enabling cookie support in Node.js fetch requests. ```bash npm install fetch-cookie ``` -------------------------------- ### File Upload Example (Node.js) Source: https://github.com/onfido/graphql-request/blob/main/README.md Illustrates how to perform a file upload using graphql-request in a Node.js environment, typically involving the 'form-data' package. ```js const { GraphQLClient } = require('graphql-request') const fs = require('fs') const FormData = require('form-data') const endpoint = 'YOUR_ENDPOINT' const client = new GraphQLClient(endpoint) const query = ` mutation uploadFile($file: Upload!) { uploadFile(file: $file) } ` const file = fs.createReadStream('./path/to/your/file.txt') const form = new FormData() form.append('file', file) const variables = { file: form, } client.request(query, variables).then(data => console.log(data)) ``` -------------------------------- ### Basic Request with `require` in Node.js Source: https://github.com/onfido/graphql-request/blob/main/README.md Demonstrates how to make a GraphQL request using `require` for module imports in a Node.js environment. Ensure `graphql-request` is installed. ```javascript const { request, gql } = require('graphql-request') async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` const data = await request(endpoint, query) console.log(JSON.stringify(data, undefined, 2)) } main().catch((error) => console.error(error)) ``` -------------------------------- ### File Upload in Node.js Source: https://github.com/onfido/graphql-request/blob/main/README.md Demonstrates how to handle file uploads in a Node.js environment using `graphql-request`. It utilizes `createReadStream` from the `fs` module to read the file. Ensure `graphql-request` is installed. ```javascript import { createReadStream } from 'fs' import { request } from 'graphql-request' const UploadUserAvatar = gql` mutation uploadUserAvatar($userId: Int!, $file: Upload!) { updateUser(id: $userId, input: { avatar: $file }) } ` request('/api/graphql', UploadUserAvatar, { userId: 1, file: createReadStream('./avatar.img'), }) ``` -------------------------------- ### File Upload in Browser Source: https://github.com/onfido/graphql-request/blob/main/README.md Example of how to perform a file upload mutation in a browser environment using `graphql-request`. It assumes an HTML input element with `id='avatar'` exists to select the file. ```javascript import { request } from 'graphql-request' const UploadUserAvatar = gql` mutation uploadUserAvatar($userId: Int!, $file: Upload!) { updateUser(id: $userId, input: { avatar: $file }) } ` request('/api/graphql', UploadUserAvatar, { userId: 1, file: document.querySelector('input#avatar').files[0], }) ``` -------------------------------- ### RawRequest Function - Full Response Source: https://context7.com/onfido/graphql-request/llms.txt Demonstrates how to use the `rawRequest` function to get the complete GraphQL response, including data, errors, extensions, headers, and status code. ```APIDOC ## POST /graphql ### Description Executes a GraphQL query or mutation and returns the full GraphQL response, including data, errors, extensions, response headers, and HTTP status code. ### Method POST ### Endpoint `https://api.example.com/graphql` ### Parameters #### Query Parameters None #### Request Body - **query** (string) - Required - The GraphQL query or mutation string. - **variables** (object) - Optional - Variables to be used with the query. ### Request Example ```typescript import { rawRequest, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` interface MovieData { Movie: { releaseDate: string actors: Array<{ name: string }> } } // Get full response with metadata const { data, errors, extensions, headers, status } = await rawRequest(endpoint, query) console.log(status) // 200 console.log(headers.get('content-type')) // "application/json" console.log(data?.Movie.releaseDate) // "2010-07-16" // Access GraphQL extensions if present if (extensions) { console.log(extensions.complexity) // Server-provided query complexity } ``` ### Response #### Success Response (200) - **data** (object) - The data returned from the GraphQL query. - **errors** (array) - An array of errors, if any occurred. - **extensions** (object) - GraphQL extensions, if provided by the server. - **headers** (Headers) - The response headers. - **status** (number) - The HTTP status code of the response. #### Response Example ```json { "data": { "Movie": { "releaseDate": "2010-07-16", "actors": [ { "name": "Leonardo DiCaprio" } ] } }, "errors": null, "extensions": { "complexity": { "queryComplexity": 10 } }, "headers": { "content-type": "application/json" }, "status": 200 } ``` ``` -------------------------------- ### Cookie Support for Node.js GraphQL Requests Source: https://github.com/onfido/graphql-request/blob/main/README.md Enables cookie support for `node-fetch` within a Node.js environment when making GraphQL requests. Requires `fetch-cookie` and `node-fetch` to be installed. ```javascript require('fetch-cookie/node-fetch')(require('node-fetch')) import { GraphQLClient, gql } from 'graphql-request' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const graphQLClient = new GraphQLClient(endpoint, { headers: { authorization: 'Bearer MY_TOKEN', }, }) const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` const data = await graphQLClient.rawRequest(query) console.log(JSON.stringify(data, undefined, 2)) } ``` -------------------------------- ### Get Full GraphQL Response with Metadata Source: https://context7.com/onfido/graphql-request/llms.txt The `rawRequest` function provides access to the complete GraphQL response, including data, errors, extensions, headers, and HTTP status. This is useful for inspecting response metadata or handling GraphQL extensions. Ensure the endpoint and query are correctly defined. ```typescript import { rawRequest, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` interface MovieData { Movie: { releaseDate: string actors: Array<{ name: string }> } } // Get full response with metadata const { data, errors, extensions, headers, status } = await rawRequest(endpoint, query) console.log(status) // 200 console.log(headers.get('content-type')) // "application/json" console.log(data?.Movie.releaseDate) // "2010-07-16" // Access GraphQL extensions if present if (extensions) { console.log(extensions.complexity) // Server-provided query complexity } ``` -------------------------------- ### GraphQL Client Usage Source: https://github.com/onfido/graphql-request/blob/main/README.md Illustrates two ways to execute GraphQL requests: using the static request function or creating a GraphQLClient instance for repeated requests with consistent configuration. ```js import { request, GraphQLClient } from 'graphql-request' // Run GraphQL queries/mutations using a static function request(endpoint, query, variables).then((data) => console.log(data)) // ... or create a GraphQL client instance to send requests const client = new GraphQLClient(endpoint, { headers: {} }) client.request(query, variables).then((data) => console.log(data)) ``` -------------------------------- ### Pass Options to Fetch Source: https://github.com/onfido/graphql-request/blob/main/README.md Configure underlying fetch options like credentials or mode during client initialization. ```javascript import { GraphQLClient, gql } from 'graphql-request' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const graphQLClient = new GraphQLClient(endpoint, { credentials: 'include', mode: 'cors', }) const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` const data = await graphQLClient.request(query) console.log(JSON.stringify(data, undefined, 2)) } main().catch((error) => console.error(error)) ``` -------------------------------- ### Using require for GraphQL Request Source: https://github.com/onfido/graphql-request/blob/main/README.md Demonstrates how to import and use the graphql-request library in a Node.js environment using require instead of ES module imports. ```js const { request, GraphQLClient } = require('graphql-request') const endpoint = 'https://api.graph.cool/simple/v1/movies' const query = ` { Movie(title: "Inception") { releaseDate actors { name } } } ` const client = new GraphQLClient(endpoint, { headers: { authorization: 'Bearer YOUR_API_TOKEN', }, }) async function runQuery() { const data = await client.request(query) console.log(JSON.stringify(data, null, 2)) } runQuery().catch(error => console.error(error)) ``` -------------------------------- ### GraphQLClient Class - Reusable Client Source: https://context7.com/onfido/graphql-request/llms.txt Shows how to create a reusable `GraphQLClient` instance with custom headers, credentials, and fetch options for making multiple requests to the same endpoint. ```APIDOC ## GraphQLClient Class ### Description Creates a reusable client instance with pre-configured settings like headers, credentials, and fetch options. Ideal for making multiple requests to the same endpoint with shared configuration. ### Method POST ### Endpoint `https://api.example.com/graphql` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **query** (string) - Required - The GraphQL query or mutation string. - **variables** (object) - Optional - Variables to be used with the query. ### Request Example ```typescript import { GraphQLClient, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' // Create client with authentication and CORS settings const client = new GraphQLClient(endpoint, { headers: { authorization: 'Bearer MY_TOKEN', }, credentials: 'include', mode: 'cors', }) const query = gql` mutation AddMovie($title: String!, $releaseDate: Int!) { insert_movies_one(object: { title: $title, releaseDate: $releaseDate }) { id title releaseDate } } ` interface CreateMovieData { insert_movies_one: { id: string title: string releaseDate: number } } const variables = { title: 'Inception', releaseDate: 2010, } // Execute mutation const data = await client.request(query, variables) console.log(data.insert_movies_one.id) // "abc123" ``` ### Response #### Success Response (200) - **data** (object) - The data returned from the GraphQL mutation. #### Response Example ```json { "data": { "insert_movies_one": { "id": "abc123", "title": "Inception", "releaseDate": 2010 } } } ``` ``` -------------------------------- ### Create Reusable GraphQL Client Instance Source: https://context7.com/onfido/graphql-request/llms.txt The `GraphQLClient` class allows creating a reusable client instance with pre-configured settings like headers, credentials, and fetch options. This is ideal for making multiple requests to the same endpoint with shared configuration. Ensure the endpoint and query are correctly defined. ```typescript import { GraphQLClient, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' // Create client with authentication and CORS settings const client = new GraphQLClient(endpoint, { headers: { authorization: 'Bearer MY_TOKEN', }, credentials: 'include', mode: 'cors', }) const query = gql` mutation AddMovie($title: String!, $releaseDate: Int!) { insert_movies_one(object: { title: $title, releaseDate: $releaseDate }) { id title releaseDate } } ` interface CreateMovieData { insert_movies_one: { id: string title: string releaseDate: number } } const variables = { title: 'Inception', releaseDate: 2010, } // Execute mutation const data = await client.request(query, variables) console.log(data.insert_movies_one.id) // "abc123" ``` -------------------------------- ### Cookie Support for Node.js Source: https://github.com/onfido/graphql-request/blob/main/README.md Shows how to enable cookie support for Node.js environments by providing a custom fetch implementation that includes cookie handling. ```js const { GraphQLClient } = require('graphql-request') const fetch = require('node-fetch-with-cookies') const endpoint = 'https://api.graph.cool/simple/v1/movies' const client = new GraphQLClient(endpoint, { fetch: fetch('https://api.graph.cool/simple/v1/movies'), }) // ... rest of your code ``` -------------------------------- ### Using a Custom Fetch Method Source: https://github.com/onfido/graphql-request/blob/main/README.md Configures the GraphQLClient to use a custom fetch implementation, allowing for advanced network configurations or integrations. ```js import { GraphQLClient } from 'graphql-request' const client = new GraphQLClient(endpoint, { fetch: (input, init) => { // Custom fetch implementation return fetch(input, init) }, }) client.request(query).then(data => console.log(data)) ``` -------------------------------- ### Authenticate via HTTP Header Source: https://github.com/onfido/graphql-request/blob/main/README.md Configure authentication headers during the initialization of the GraphQLClient. ```javascript import { GraphQLClient, gql } from 'graphql-request' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const graphQLClient = new GraphQLClient(endpoint, { headers: { authorization: 'Bearer MY_TOKEN', }, }) const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` const data = await graphQLClient.request(query) console.log(JSON.stringify(data, undefined, 2)) } main().catch((error) => console.error(error)) ``` -------------------------------- ### Request Function - Simple Query Source: https://context7.com/onfido/graphql-request/llms.txt Demonstrates how to execute a simple GraphQL query using the `request` function with typed response. ```APIDOC ## POST /graphql ### Description Executes a GraphQL query or mutation against a specified endpoint and returns a promise that resolves directly to the data portion of the response. ### Method POST ### Endpoint `https://api.example.com/graphql` ### Parameters #### Query Parameters None #### Request Body - **query** (string) - Required - The GraphQL query or mutation string. - **variables** (object) - Optional - Variables to be used with the query. ### Request Example ```typescript import { request, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' const query = gql` query getMovie($title: String!) { Movie(title: $title) { releaseDate actors { name } } } ` const variables = { title: 'Inception', } interface MovieData { Movie: { releaseDate: string actors: Array<{ name: string }> } } // Execute request with typed response const data = await request(endpoint, query, variables) console.log(data.Movie.releaseDate) // "2010-07-16" console.log(data.Movie.actors[0].name) // "Leonardo DiCaprio" ``` ### Response #### Success Response (200) - **data** (object) - The data returned from the GraphQL query. #### Response Example ```json { "data": { "Movie": { "releaseDate": "2010-07-16", "actors": [ { "name": "Leonardo DiCaprio" } ] } } } ``` ``` -------------------------------- ### Implement Custom Fetch for GraphQL Requests Source: https://context7.com/onfido/graphql-request/llms.txt Support custom fetch implementations for scenarios like cookie handling in Node.js, request logging, or using alternative HTTP clients. Integrates with libraries like fetch-cookie. ```typescript import { fetch } from 'cross-fetch' import fetchCookie from 'fetch-cookie' import { GraphQLClient, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' // Create a cookie-enabled fetch for session handling const fetchWithCookies = fetchCookie(fetch) const client = new GraphQLClient(endpoint, { fetch: fetchWithCookies, headers: { 'user-agent': 'MyApp/1.0', }, }) // Login mutation - cookies will be stored automatically const loginMutation = gql` mutation login($email: String!, $password: String!) { login(email: $email, password: $password) { success user { id email } } } ` const loginResult = await client.request(loginMutation, { email: 'user@example.com', password: 'secret', }) // Subsequent requests will include session cookies const meQuery = gql` { me { id email profile { name } } } ` const userData = await client.request(meQuery) console.log(userData.me.profile.name) ``` -------------------------------- ### Abort GraphQL Request with AbortController Source: https://github.com/onfido/graphql-request/blob/main/README.md Demonstrates how to abort a GraphQL request using AbortController and setTimeout. Ensure a global fetch is available or polyfilled in your environment. ```tsx import { GraphQLClient } from 'graphql-request' const client = new GraphQLClient(endpoint) function call() { const controller = new AbortController() const { signal } = controller setTimeout(() => controller.abort(), 5000) // abort in 5 seconds return client.request(query, variables, { signal }) } ``` -------------------------------- ### Receiving Raw GraphQL Response Source: https://github.com/onfido/graphql-request/blob/main/README.md Shows how to use the `rawRequest` method to access not only `data` and `errors` but also `extensions`, `headers`, and `status` from a GraphQL response. This is useful when you need more than just the query results. ```javascript import { rawRequest, gql } from 'graphql-request' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const query = gql` { Movie(title: "Inception") { releaseDate actors { name } } } ` const { data, errors, extensions, headers, status } = await rawRequest(endpoint, query) console.log(JSON.stringify({ data, errors, extensions, headers, status }, undefined, 2)) } ``` -------------------------------- ### Execute GraphQL Mutations Source: https://github.com/onfido/graphql-request/blob/main/README.md Perform mutations by passing the mutation string and variables to the request method. ```javascript import { GraphQLClient, gql } from 'graphql-request' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const graphQLClient = new GraphQLClient(endpoint, { headers: { authorization: 'Bearer MY_TOKEN', }, }) const mutation = gql` mutation AddMovie($title: String!, $releaseDate: Int!) { insert_movies_one(object: { title: $title, releaseDate: $releaseDate }) { title releaseDate } } ` const variables = { title: 'Inception', releaseDate: 2010, } const data = await graphQLClient.request(mutation, variables) console.log(JSON.stringify(data, undefined, 2)) } main().catch((error) => console.error(error)) ``` -------------------------------- ### Define GraphQL Queries with gql Tag Source: https://context7.com/onfido/graphql-request/llms.txt Use the gql template tag for IDE tooling support (syntax highlighting, formatting, autocompletion) without runtime parsing overhead. Supports string interpolation for fragment composition. ```typescript import { request, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' // Use gql for IDE support - syntax highlighting, prettier formatting const fragment = gql` fragment MovieFields on Movie { id title releaseDate } ` const query = gql` ${fragment} query getMovies($limit: Int!) { movies(limit: $limit) { ...MovieFields actors { name } } } ` // gql tag allows string interpolation for fragment composition const data = await request(endpoint, query, { limit: 10 }) console.log(data.movies) // Array of movies with fragment fields ``` -------------------------------- ### Incrementally Set Headers Source: https://github.com/onfido/graphql-request/blob/main/README.md Update or set headers on an existing GraphQLClient instance using setHeader or setHeaders. ```javascript import { setHeaders, setHeader, GraphQLClient } from 'graphql-request' const client = new GraphQLClient(endpoint) // Set a single header client.setHeader('authorization', 'Bearer MY_TOKEN') // Override all existing headers client.setHeaders({ authorization: 'Bearer MY_TOKEN', anotherheader: 'header_value', }) ``` -------------------------------- ### Abort GraphQL Requests with AbortController Source: https://context7.com/onfido/graphql-request/llms.txt Cancel requests using the standard AbortController API by passing the signal in init options. Useful for implementing timeouts or cancelling requests when components unmount. ```typescript import { GraphQLClient, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' const client = new GraphQLClient(endpoint) const query = gql` { slowQuery { results } } ` async function fetchWithTimeout(timeoutMs: number) { const controller = new AbortController() const { signal } = controller // Set timeout to abort request const timeoutId = setTimeout(() => controller.abort(), timeoutMs) try { const data = await client.request(query, undefined, { signal }) clearTimeout(timeoutId) return data } catch (error) { if (error.name === 'AbortError') { console.log('Request was aborted due to timeout') } throw error } } // Abort if request takes longer than 5 seconds const data = await fetchWithTimeout(5000) ``` -------------------------------- ### Receiving Raw Response Source: https://github.com/onfido/graphql-request/blob/main/README.md Demonstrates how to configure the GraphQLClient to return the raw Response object instead of parsing the JSON body, useful for inspecting response headers or status codes. ```js import { GraphQLClient } from 'graphql-request' const client = new GraphQLClient(endpoint, { fetch: (input, init) => { return fetch(input, init) }, // Set this to true to receive a raw Response object raw: true, }) client.request(query).then(response => { console.log(response.status) return response.json() }).then(data => console.log(data)) ``` -------------------------------- ### Override Default Headers on Per-Request Basis Source: https://context7.com/onfido/graphql-request/llms.txt Customize headers for individual requests by passing them in the `init` options. These headers merge with and override the client's default headers. ```typescript import { GraphQLClient, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' const client = new GraphQLClient(endpoint, { headers: { authorization: 'Bearer DEFAULT_TOKEN', 'x-app-version': '1.0.0', }, }) const query = gql` query getSecretData($id: ID!) { secretResource(id: $id) { sensitiveData } } ` // Override authorization for this specific request const data = await client.request( query, { id: 'resource-123' }, { headers: { authorization: 'Bearer ELEVATED_PRIVILEGE_TOKEN', 'x-request-id': 'audit-12345', }, } ) console.log(data.secretResource.sensitiveData) ``` -------------------------------- ### Support File Uploads with GraphQL Multipart Request Source: https://context7.com/onfido/graphql-request/llms.txt Upload files by passing `File` objects (browser) or `ReadStream` (Node.js) in variables. The library automatically constructs the multipart form data. ```typescript import { createReadStream } from 'fs' import { request, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' // Browser file upload const uploadMutation = gql` mutation uploadUserAvatar($userId: Int!, $file: Upload!) { updateUser(id: $userId, input: { avatar: $file }) { id avatarUrl } } ` // In browser - use File from input element const fileInput = document.querySelector('input#avatar') as HTMLInputElement const browserData = await request(endpoint, uploadMutation, { userId: 1, file: fileInput.files[0], }) console.log('Avatar URL:', browserData.updateUser.avatarUrl) // In Node.js - use ReadStream const nodeData = await request(endpoint, uploadMutation, { userId: 1, file: createReadStream('./avatar.png'), }) console.log('Avatar URL:', nodeData.updateUser.avatarUrl) ``` -------------------------------- ### Handle Errors Source: https://github.com/onfido/graphql-request/blob/main/README.md Wrap requests in try-catch blocks to handle GraphQL execution errors. ```javascript import { request, gql } from 'graphql-request' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const query = gql` { Movie(title: "Inception") { releaseDate actors { fullname # "Cannot query field 'fullname' on type 'Actor'. Did you mean 'name'?" } } } ` try { const data = await request(endpoint, query) console.log(JSON.stringify(data, undefined, 2)) } catch (error) { console.error(JSON.stringify(error, undefined, 2)) process.exit(1) } } main().catch((error) => console.error(error)) ``` -------------------------------- ### Set and Update Client Headers Source: https://context7.com/onfido/graphql-request/llms.txt Dynamically update client headers using setHeader and setHeaders. Useful for authentication tokens that change during the application lifecycle. Returns the client instance for chaining. ```typescript import { GraphQLClient, gql } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' const client = new GraphQLClient(endpoint) // Set a single header (returns client for chaining) client.setHeader('authorization', 'Bearer INITIAL_TOKEN') // Later, update to a new token client.setHeader('authorization', 'Bearer REFRESHED_TOKEN') // Override all headers at once client.setHeaders({ authorization: 'Bearer MY_TOKEN', 'x-custom-header': 'custom-value', 'x-request-id': 'req-12345', }) const query = gql` { currentUser { id email } } ` // All subsequent requests use the configured headers const data = await client.request(query) console.log(data.currentUser.email) ``` -------------------------------- ### Execute a GraphQL Query with Typed Response Source: https://context7.com/onfido/graphql-request/llms.txt Use the `request` function for simple queries. It returns a promise that resolves directly to the data portion of the response. Ensure the endpoint, query, and variables are correctly defined. ```typescript import { request, gql } from '@onfido/graphql-request' // Simple query with string const endpoint = 'https://api.example.com/graphql' const query = gql` query getMovie($title: String!) { Movie(title: $title) { releaseDate actors { name } } } ` const variables = { title: 'Inception', } interface MovieData { Movie: { releaseDate: string actors: Array<{ name: string }> } } // Execute request with typed response const data = await request(endpoint, query, variables) console.log(data.Movie.releaseDate) // "2010-07-16" console.log(data.Movie.actors[0].name) // "Leonardo DiCaprio" ``` -------------------------------- ### Pass Headers per Request Source: https://github.com/onfido/graphql-request/blob/main/README.md Provide custom headers directly to the request or rawRequest methods to override client-level headers. ```javascript import { GraphQLClient } from 'graphql-request' const client = new GraphQLClient(endpoint) const query = gql` query getMovie($title: String!) { Movie(title: $title) { releaseDate actors { name } } } ` const variables = { title: 'Inception', } const requestHeaders = { authorization: 'Bearer MY_TOKEN', } // Overrides the clients headers with the passed values const data = await client.request(query, variables, requestHeaders) ``` -------------------------------- ### Use GraphQL Document Variables Source: https://github.com/onfido/graphql-request/blob/main/README.md Pass variables to queries using the request function. ```javascript import { request, gql } from 'graphql-request' async function main() { const endpoint = 'https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr' const query = gql` query getMovie($title: String!) { Movie(title: $title) { releaseDate actors { name } } } ` const variables = { title: 'Inception', } const data = await request(endpoint, query, variables) console.log(JSON.stringify(data, undefined, 2)) } main().catch((error) => console.error(error)) ``` -------------------------------- ### Handle GraphQL and HTTP Errors with ClientError Source: https://context7.com/onfido/graphql-request/llms.txt Catch and inspect `ClientError` to access GraphQL errors, HTTP status, response headers, and original request details. This is useful for debugging and implementing robust error handling logic. ```typescript import { request, gql, ClientError } from '@onfido/graphql-request' const endpoint = 'https://api.example.com/graphql' const query = gql` { Movie(title: "Inception") { releaseDate actors { fullname # This field doesn't exist - will cause GraphQL error } } } ` try { const data = await request(endpoint, query) console.log(data) } catch (error) { if (error instanceof ClientError) { // Access GraphQL errors console.log('GraphQL Errors:', error.response.errors) // [{ message: "Cannot query field 'fullname' on type 'Actor'. Did you mean 'name'?", locations: [...], path: [...] }] // Access HTTP status console.log('HTTP Status:', error.response.status) // 200 (GraphQL errors still return 200) // Access response headers console.log('Headers:', error.response.headers) // Access original request for debugging console.log('Query:', error.request.query) console.log('Variables:', error.request.variables) } else { // Network error or other non-GraphQL error console.error('Network Error:', error.message) } process.exit(1) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.