|
| 1 | +import { print } from 'graphql/language/printer' |
| 2 | +import type { TadaDocumentNode, ResultOf } from 'gql.tada' |
| 3 | +import type { QueryConfig } from './graphqlQuery.types' |
| 4 | +import { appConfig } from '../appConfig' |
| 5 | + |
| 6 | +/** --- graphqlQuery --------------------------------------------------------------------------- */ |
| 7 | +/** -i- Isomorphic graphql request, uses the graphql endpoint in browser & mobile, but the executable schema serverside */ |
| 8 | +export const graphqlQuery = async <T extends TadaDocumentNode, R = ResultOf<T>>(query: T, config?: QueryConfig<T>) => { |
| 9 | + // Config |
| 10 | + const { variables, headers, graphqlEndpoint } = config || {} |
| 11 | + |
| 12 | + // Flags |
| 13 | + const isServer = typeof window === 'undefined' |
| 14 | + |
| 15 | + // Vars |
| 16 | + const queryString = print(query) |
| 17 | + |
| 18 | + // -- Server: Execute query with lazy loaded schema -- |
| 19 | + |
| 20 | + if (isServer) { |
| 21 | + try { |
| 22 | + const [ |
| 23 | + { graphql }, |
| 24 | + { executableSchema }, |
| 25 | + ] = await Promise.all([ |
| 26 | + import('graphql'), |
| 27 | + import('./schema'), |
| 28 | + ]) |
| 29 | + const { data } = await graphql({ |
| 30 | + schema: executableSchema, |
| 31 | + source: queryString, |
| 32 | + variableValues: variables, |
| 33 | + }) as { data: R } |
| 34 | + return data |
| 35 | + } catch (error) { |
| 36 | + throw new Error(error) |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // -- Browser: Execute query with fetch -- |
| 41 | + |
| 42 | + try { |
| 43 | + const { graphURL } = appConfig |
| 44 | + const fetchURL = graphqlEndpoint || graphURL |
| 45 | + const res = await fetch(fetchURL, { |
| 46 | + method: 'POST', |
| 47 | + headers: { |
| 48 | + 'Content-Type': 'application/json', |
| 49 | + ...headers, |
| 50 | + }, |
| 51 | + body: JSON.stringify({ query: queryString, variables }), |
| 52 | + }) |
| 53 | + const { data, errors } = await res.json() |
| 54 | + if (errors) throw new Error(errors[0].message) |
| 55 | + return data as R |
| 56 | + } catch (error) { |
| 57 | + throw new Error(error) |
| 58 | + } |
| 59 | +} |
| 60 | + |
0 commit comments