The
createClient
gives you an SDK client for your GraphQL APItypescriptimport { createClient, } from './generated_dir' const client = createClient({ url: '<http://your-api>', headers: { Authorization: 'Bearer xxx', }, }) await client.query({ repository: {__args: { name: 'genql', owner: 'remorses' }, name: true }, })
Pass a custom fetch
function
NodeJs 16 and lower doesnโt have a global fetch function so you may need to pass one as a prop
javascriptimport { createClient, } from './generated_dir' import { fetch } from 'undici' const client = createClient({ url: '<http://your-api>', fetch, headers: { Authorization: 'Bearer xxx', }, })
Change headers at runtime
You can pass a function to the headers field to pull the headers at query time, this way you can for example take the auth token from localStorage
typescriptimport { createClient } from './generated_dir' const client = createClient({ url: '<http://your-api>', headers: () => ({ Authorization: localStorage.get('authToken'), }), })
Using a custom fetcher
You can use your own http fetcher function, must be of type
(operation: {query, variables}) => Promise<{data, errors}>
typescriptimport { createClient } from './generated_dir' const client = createClient({ fetcher: (operation) => { return fetch('<http://your-api>', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(operation), }).then((response) => response.json()) }, })