UNPKG

ahau-graphql-client

Version:

apollo graphql client for ahau apps

60 lines (51 loc) 1.53 kB
const { ApolloClient, InMemoryCache, gql } = require('@apollo/client/core') const { createUploadLink } = require('apollo-upload-client') // partners with graphql-upload module.exports = class AhauGraphqlClient extends ApolloClient { constructor (uri, opts = {}) { if (!uri) throw new Error(`graphql uri required, got ${uri}`) if (typeof uri === 'number') uri = `http://localhost:${uri}/graphql` const isBrowser = typeof window !== 'undefined' if (!isBrowser && !opts.fetch) throw new Error('when not in the browser, opts.fetch must be provided') const { possibleTyes = {}, fetch, apolloClient = {} } = opts const isTesting = ( process.env.NODE_ENV === 'test' || opts.isTesting ) super({ // ssrMode: !isBrowser, cache: new InMemoryCache({ possibleTyes, // see https://www.apollographql.com/docs/react/data/fragments/ addTypename: !isTesting // in testing this removes __typename from results }), link: createUploadLink({ uri, // fetch ...(fetch ? { fetch } : {}) }), connectToDevTools: true, ...apolloClient }) } query ({ query, ...args }) { return super.query({ query: toGQL(query), fetchPolicy: 'no-cache', ...args }) } mutate ({ mutation, ...args }) { return super.mutate({ mutation: toGQL(mutation), ...args }) } } function toGQL (input) { return typeof input === 'string' ? gql`${input}` : input }