Files
dancefinder-app/plugins/apollo.js
T

166 lines
4.3 KiB
JavaScript

import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { setContext } from 'apollo-link-context'
import { reactive, toRefs } from '@vue/composition-api'
import useAuth from './auth'
let instance = null
const apiUrl = process.env.graphqlApi || '/query'
const httpLink = createHttpLink({
uri: apiUrl
})
const getToken = async options => {
const { getTokenSilently, isAuthenticated } = useAuth()
if (isAuthenticated.value) {
return getTokenSilently.value(options)
}
return options
}
const authLink = setContext(async (_, { headers }) => {
const token = await getToken()
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
}
})
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network'
}
}
})
instance = client
export const useMutation = (mutation, options) => {
const out = reactive({
data: {},
error: null,
loading: false
})
const doMutate = mutateOptions =>
new Promise((resolve, reject) => {
out.loading = true
instance
.mutate({
mutation,
...options,
...mutateOptions
})
.then(result => {
out.loading = false
out.data = result.data
resolve(result)
})
.catch(e => {
out.loading = false
out.error = e
reject(e)
})
})
return [doMutate, toRefs(out)]
}
export const useLazyQuery = (query, options) => {
let watchedQuery = null
const out = reactive({
data: {},
error: null,
loading: false
})
const doQuery = queryOptions =>
new Promise((resolve, reject) => {
out.loading = true
const effectiveOptions = {
query,
...(options || {}),
...(queryOptions || {})
}
watchedQuery = instance.watchQuery(effectiveOptions)
watchedQuery.subscribe(
({ loading, data }) => {
out.loading = loading
out.data = data || {}
out.error = null
resolve(data)
},
error => {
out.loading = false
out.error = error
reject(error)
}
)
})
out.refetch = variables => {
const opts = {}
if (variables) opts.variables = variables
doQuery(opts)
}
out.startPolling = interval => doQuery({ pollInterval: interval })
out.stopPolling = () => {
if (watchedQuery) {
watchedQuery.stopPolling()
}
}
return [doQuery, toRefs(out)]
}
export const useQuery = (query, options) => {
const [doQuery, out] = useLazyQuery(query, options)
doQuery()
return out
}
// import { execute, makePromise, ApolloLink, Observable } from 'apollo-link';
// import { HttpLink } from 'apollo-link-http';
// const { includeCredentials } = require('./middleware');
// import { onError } from 'apollo-link-error';
//
// const defaultGraphUri = process.env.graphqlApi || 'https://shiny-gateway.unbound.se';
// const httpLink = new HttpLink({ uri: defaultGraphUri, fetch: includeCredentials, credentials: 'same-origin' });
// const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
// if (graphQLErrors) {
// console.log('GraphQL errors:', graphQLErrors);
// // for (let err of graphQLErrors) {
// // switch (err.extensions.code) {
// // case 'UNAUTHENTICATED':
// // // error code is set to UNAUTHENTICATED
// // // when AuthenticationError thrown in resolver
// //
// // // modify the operation context with a new token
// // }
// // }
// }
// if (networkError) {
// if (networkError.statusCode === 401) {
// return new Observable(observer => {
// // webAuth.checkSession(() => {
// const subscriber = {
// next: observer.next.bind(observer),
// error: observer.error.bind(observer),
// complete: observer.complete.bind(observer)
// };
//
// // Retry last failed request
// forward(operation).subscribe(subscriber);
// // }, (err) => {
// // console.log(err);
// // observer.error(err)
// // });
// });
// }
// }
// }
// );