Skip to content

Instantly share code, notes, and snippets.

@rickyalmeidadev
Last active September 8, 2021 17:43
Show Gist options
  • Save rickyalmeidadev/c70e4effbe0402679c17a8aa15af1371 to your computer and use it in GitHub Desktop.
Save rickyalmeidadev/c70e4effbe0402679c17a8aa15af1371 to your computer and use it in GitHub Desktop.
GraphQL client factory for Next.js
export type GraphQLQuery = string
export type GraphQLMutation = string
export type Variables = {
[key: string]: any
}
type QueryBody = {
query: GraphQLQuery
variables?: Variables
}
type MutationBody = {
mutation: GraphQLMutation
variables?: Variables
}
export type Body = QueryBody | MutationBody
export type GraphqlTag = typeof String.raw
export type GraphQLClient = {
query: <T = any>(query: GraphQLQuery, variables?: Variables) => Promise<T>
mutate: <T = any>(mutation: GraphQLMutation, variables?: Variables) => Promise<T>
}
import Cookies from 'js-cookie'
import type {GetServerSidePropsContext} from 'next'
import type {
Body,
GraphQLClient,
GraphQLMutation,
GraphQLQuery,
GraphqlTag,
Variables
} from './make-graphql-client.d'
const makeGraphQLClient = (
context?: GetServerSidePropsContext
): {client: GraphQLClient; graphql: GraphqlTag} => {
const token = context ? context.req.cookies.token : Cookies.get('token')
const request = async (body: Body) => {
const response = await fetch('http://localhost:4000/graphql-v2', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
...(token && {'Authorization': `Bearer ${token}`})
},
body: JSON.stringify(body)
})
const {data, errors} = await response.json()
if (errors) {
const [{message}] = errors
throw new Error(message)
}
return data
}
return {
client: {
query: async (query: GraphQLQuery, variables?: Variables) =>
request({query, variables}),
mutate: async (mutation: GraphQLMutation, variables?: Variables) =>
request({mutation, variables})
},
graphql: String.raw
}
}
export default makeGraphQLClient
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment