chore: make auth and apollo a bit more reactive

This commit is contained in:
2020-04-06 10:19:18 +02:00
parent aa557faf22
commit cc9968bd06
14 changed files with 1327 additions and 360 deletions
+107 -111
View File
@@ -1,39 +1,43 @@
import { ApolloClient } from 'apollo-client'
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
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'
import { useAuth } from './auth'
import { computed, reactive, toRefs } from '@vue/composition-api'
import introspectionQueryResultData from '../fragmentTypes.json'
const fragmentMatcher = new IntrospectionFragmentMatcher({
introspectionQueryResultData
})
let instance = null
const apiUrl = process.env.graphqlApi || '/query'
const cache = new InMemoryCache({ fragmentMatcher })
const httpLink = createHttpLink({
uri: apiUrl
})
const getToken = async options => {
const { getTokenSilently, isAuthenticated } = useAuth()
if (isAuthenticated.value) {
return getTokenSilently.value(options)
}
return options
const getToken = async (options) => {
const { getTokenSilently } = useAuth()
return getTokenSilently.value(options)
}
const authLink = setContext(async (_, { headers }) => {
const token = await getToken()
return {
return getToken().then(token => ({
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
}
}))
})
const client = new ApolloClient({
console.log('Setting up Apollo')
instance = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
cache,
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network'
@@ -41,79 +45,86 @@ const client = new ApolloClient({
}
})
instance = client
const merge = (target, ...source) => {
const sources = source instanceof Array ? source : [source]
return sources.reduce((acc, source) => {
for (const key of Object.keys(source)) {
if (source[key] instanceof Object) Object.assign(source[key], merge(acc[key], source[key]))
}
return Object.assign(acc, source)
}, target || {})
}
export const useMutation = (mutation, options) => {
const opts = options
const doMutate = options => new Promise((resolve, reject) => {
out.loading = true
instance.mutate({
mutation,
...opts,
...options
})
.then(result => {
out.loading = false
out.data = result.data
resolve(result)
})
.catch(e => {
out.loading = false
out.error = e
reject(e)
})
})
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) => {
const opts = options
let watchedQuery = null
const doQuery = options => new Promise((resolve, reject) => {
out.loading = true
const effectiveOptions = merge({ query }, opts || {}, options || {})
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)
})
})
const refetch = variables => {
doQuery({
variables: {
...(variables || {})
}
})
}
const startPolling = interval => doQuery({ pollInterval: interval })
const stopPolling = () => {
if (watchedQuery) {
watchedQuery.stopPolling()
}
}
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)]
return [doQuery, {
...toRefs(out),
refetch,
startPolling,
stopPolling
}]
}
export const useQuery = (query, options) => {
@@ -122,44 +133,29 @@ export const useQuery = (query, options) => {
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)
// // });
// });
// }
// }
// }
// );
export const useResult = (result, defaultValue, pick) => {
return computed(() => {
const value = result.value
if (value) {
if (pick) {
try {
return pick(value)
} catch (e) {
// Silent error
}
} else {
const keys = Object.keys(value)
if (keys.length === 1) {
// Automatically take the only key in result data
return value[keys[0]]
} else {
// Return entire result data
return value
}
}
} else {
return defaultValue
}
})
}