chore: make auth and apollo a bit more reactive
This commit is contained in:
+107
-111
@@ -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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+54
-43
@@ -7,10 +7,10 @@ const DEFAULT_REDIRECT_CALLBACK = () =>
|
||||
|
||||
let instance
|
||||
|
||||
const params = new URL(window.location).searchParams
|
||||
const params = (new URL(window.location)).searchParams
|
||||
const domain = params.get('domain') || 'unbound.eu.auth0.com'
|
||||
|
||||
export default (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
|
||||
export const useAuth = (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
|
||||
if (instance) {
|
||||
return toRefs(instance)
|
||||
}
|
||||
@@ -34,23 +34,23 @@ export default (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
|
||||
this.popupOpen = true
|
||||
|
||||
try {
|
||||
await instance.auth0Client.loginWithPopup(o)
|
||||
await instance.auth0Client.then(client => client.loginWithPopup(o))
|
||||
} catch (e) {
|
||||
// eslint-disable-next-line
|
||||
console.error(e);
|
||||
console.error(e)
|
||||
} finally {
|
||||
instance.popupOpen = false
|
||||
}
|
||||
|
||||
instance.user = await instance.auth0Client.getUser()
|
||||
instance.user = await instance.auth0Client.then(client => client.getUser())
|
||||
instance.isAuthenticated = true
|
||||
},
|
||||
/** Handles the callback when logging in using a redirect */
|
||||
handleRedirectCallback: async () => {
|
||||
instance.loading = true
|
||||
try {
|
||||
await instance.auth0Client.handleRedirectCallback()
|
||||
instance.user = await instance.auth0Client.getUser()
|
||||
await instance.auth0Client.then(client => client.handleRedirectCallback())
|
||||
instance.user = await instance.auth0Client.then(client => client.getUser())
|
||||
instance.isAuthenticated = true
|
||||
} catch (e) {
|
||||
instance.error = e
|
||||
@@ -60,62 +60,73 @@ export default (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
|
||||
},
|
||||
/** Authenticates the user using the redirect method */
|
||||
loginWithRedirect: o => {
|
||||
return instance.auth0Client.loginWithRedirect(o)
|
||||
return instance.auth0Client.then(client => client.loginWithRedirect(o))
|
||||
},
|
||||
/** Returns all the claims present in the ID token */
|
||||
getIdTokenClaims: o => {
|
||||
return instance.auth0Client.getIdTokenClaims(o)
|
||||
return instance.auth0Client.then(client => client.getIdTokenClaims(o))
|
||||
},
|
||||
/** Returns the access token. If the token is invalid or missing, a new one is retrieved */
|
||||
getTokenSilently: o => {
|
||||
return instance.auth0Client.getTokenSilently(o)
|
||||
return instance.auth0Client.then(client => {
|
||||
return client.getTokenSilently(o)
|
||||
})
|
||||
},
|
||||
/** Gets the access token using a popup window */
|
||||
getTokenWithPopup: o => {
|
||||
return instance.auth0Client.getTokenWithPopup(o)
|
||||
return instance.auth0Client.then(client => client.getTokenWithPopup(o))
|
||||
},
|
||||
/** Logs the user out and removes their session on the authorization server */
|
||||
logout: o => {
|
||||
return instance.auth0Client.logout(o)
|
||||
return instance.auth0Client.then(client => client.logout(o))
|
||||
}
|
||||
})
|
||||
|
||||
const fetchUser = () => {
|
||||
instance.auth0Client.isAuthenticated().then(a => {
|
||||
instance.isAuthenticated = a
|
||||
instance.auth0Client.getUser().then(u => {
|
||||
instance.user = u
|
||||
instance.loading = false
|
||||
instance.auth0Client
|
||||
.then(client => client.isAuthenticated())
|
||||
.then(a => {
|
||||
instance.isAuthenticated = a
|
||||
instance.auth0Client
|
||||
.then(client => client.getUser()
|
||||
.then(u => {
|
||||
instance.user = u
|
||||
instance.loading = false
|
||||
}))
|
||||
})
|
||||
})
|
||||
}
|
||||
// Create a new instance of the SDK client using members of the given options object
|
||||
createAuth0Client(options).then(client => {
|
||||
instance.loading = true
|
||||
instance.auth0Client = client
|
||||
try {
|
||||
// If the user is returning to the app after authentication..
|
||||
if (
|
||||
window.location.search.includes('code=') &&
|
||||
window.location.search.includes('state=')
|
||||
) {
|
||||
// handle the redirect and retrieve tokens
|
||||
instance.auth0Client.handleRedirectCallback().then(appState => {
|
||||
// Notify subscribers that the redirect callback has happened, passing the appState
|
||||
// (useful for retrieving any pre-authentication state)
|
||||
onRedirectCallback(appState)
|
||||
// Initialize our internal authentication state
|
||||
// Create a new instance of the SDK client using members of the given options object
|
||||
instance.auth0Client = createAuth0Client(options)
|
||||
instance.auth0Client
|
||||
.then(client => {
|
||||
instance.loading = true
|
||||
// instance.auth0Client = client
|
||||
try {
|
||||
// If the user is returning to the app after authentication..
|
||||
if (
|
||||
window.location.search.includes('code=') &&
|
||||
window.location.search.includes('state=')
|
||||
) {
|
||||
console.log('location search', window.location.search)
|
||||
// handle the redirect and retrieve tokens
|
||||
client.handleRedirectCallback()
|
||||
.then(appState => {
|
||||
// Notify subscribers that the redirect callback has happened, passing the appState
|
||||
// (useful for retrieving any pre-authentication state)
|
||||
onRedirectCallback(appState)
|
||||
// Initialize our internal authentication state
|
||||
fetchUser()
|
||||
})
|
||||
.catch(e => console.error('error handling redirect callback', e))
|
||||
} else {
|
||||
fetchUser()
|
||||
})
|
||||
} else {
|
||||
fetchUser()
|
||||
}
|
||||
} catch (e) {
|
||||
instance.error = e
|
||||
} finally {
|
||||
instance.loading = false
|
||||
}
|
||||
} catch (e) {
|
||||
instance.error = e
|
||||
} finally {
|
||||
instance.loading = false
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return toRefs(instance)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user