chore: switch to apollo-composable

This commit is contained in:
2020-06-21 17:59:14 +02:00
parent 5aeb510231
commit 84843cc3ed
10 changed files with 3033 additions and 2446 deletions
+160 -157
View File
@@ -1,9 +1,10 @@
<template> <template>
<div :key="isAuthenticated"> <div :key="isAuthenticated">
<span v-text="isAuthenticated"/>
<v-container fluid grid-list-md class="app-fade-in" :key="range"> <v-container fluid grid-list-md class="app-fade-in" :key="range">
<v-layout row wrap v-if="!isAuthenticated"> <v-layout row wrap v-if="!isAuthenticated">
<v-flex xs12> <v-flex xs12>
<p><b v-text="$t('events.login')" /></p> <p><b v-text="$t('events.login')"/></p>
</v-flex> </v-flex>
</v-layout> </v-layout>
<v-layout row wrap> <v-layout row wrap>
@@ -16,10 +17,11 @@
<v-tooltip top slot="append-outer"> <v-tooltip top slot="append-outer">
<template v-slot:activator="{ on }"> <template v-slot:activator="{ on }">
<v-icon v-on="on" v-on:click="fetchAddress()" <v-icon v-on="on" v-on:click="fetchAddress()"
>mdi-crosshairs-gps</v-icon >mdi-crosshairs-gps
</v-icon
> >
</template> </template>
<span v-text="$t('origins.fetchAddress')" /> <span v-text="$t('origins.fetchAddress')"/>
</v-tooltip> </v-tooltip>
<v-tooltip top slot="prepend" v-if="isAuthenticated"> <v-tooltip top slot="prepend" v-if="isAuthenticated">
<template v-slot:activator="{ on }"> <template v-slot:activator="{ on }">
@@ -27,10 +29,11 @@
v-on="on" v-on="on"
:disabled="!origin" :disabled="!origin"
v-on:click="saveOrigin(origin)" v-on:click="saveOrigin(origin)"
>mdi-bookmark-plus-outline</v-icon >mdi-bookmark-plus-outline
</v-icon
> >
</template> </template>
<span v-text="$t('origins.save')" /> <span v-text="$t('origins.save')"/>
</v-tooltip> </v-tooltip>
</v-text-field> </v-text-field>
</v-flex> </v-flex>
@@ -77,168 +80,168 @@
</template> </template>
<script> <script>
import { useRouter, useMutations } from '@u3u/vue-hooks' import { useMutations, useRouter } from '@u3u/vue-hooks'
import { computed, ref, watch } from '@vue/composition-api' import { computed, ref, watch } from '@vue/composition-api'
import useAuth from '../../../plugins/auth' import { useAuth } from '../../../plugins/auth'
import List from './List' import List from './List'
import { useLazyQuery, useMutation, useResult } from '../../../plugins/apollo' import { useMutation, useQuery, useResult } from '@vue/apollo-composable'
import { import {
fetchAddress, fetchAddress,
findEvents, findEvents,
saveOrigin, saveOrigin,
toggleIgnoreBand, toggleIgnoreBand,
toggleIgnoreCity, toggleIgnoreCity,
toggleIgnoreDanceHall, toggleIgnoreDanceHall,
toggleIgnoreMunicipality, toggleIgnoreMunicipality,
toggleIgnoreState toggleIgnoreState
} from '../../../utils/graph-client' } from '../../../utils/graph-client'
import { useTranslation } from '../../../plugins/i18n' import { useTranslation } from '../../../plugins/i18n'
export default { export default {
components: { components: {
List List
}, },
setup() { setup() {
const { setTitle } = useMutations(['setTitle']) const { setTitle } = useMutations(['setTitle'])
const { t } = useTranslation() const { t } = useTranslation()
setTitle(t('app.links.events')) setTitle(t('app.links.events'))
const { loading: authLoading, isAuthenticated } = useAuth() const { loading: authLoading, isAuthenticated } = useAuth()
const { route, router } = useRouter() const { route, router } = useRouter()
const range = computed({ const range = computed({
get: () => route.value.query.range || 'ONE_WEEK', get: () => route.value.query.range || 'ONE_WEEK',
set: value => router.push(`/?range=${value}`) set: value => router.push(`/?range=${value}`)
}) })
const [query, { data }] = useLazyQuery(findEvents) const enabled = ref(false)
const events = useResult(data, [], result => result.events) const { result: data, refetch } = useQuery(findEvents, { includeOrigins: false }, () => ({ enabled: enabled.value }))
const origins = useResult(data, [], result => result.origins) const events = useResult(data, [], result => result.events)
watch( const origins = useResult(data, [], result => result.origins)
() => range.value, watch(
r => { range,
query({ r => {
variables: { enabled.value = true
console.log('isAuthenticated', isAuthenticated.value)
refetch({
range: r, range: r,
includeOrigins: isAuthenticated.value includeOrigins: isAuthenticated.value || false
} })
}) },
}, { lazy: false }
{ lazy: false } )
) const submitting = ref(true)
const submitting = ref(true) const ranges = [
const ranges = [ { name: '1 vecka', value: 'ONE_WEEK' },
{ name: '1 vecka', value: 'ONE_WEEK' }, { name: '2 veckor', value: 'TWO_WEEKS' },
{ name: '2 veckor', value: 'TWO_WEEKS' }, { name: '1 månad', value: 'ONE_MONTH' },
{ name: '1 månad', value: 'ONE_MONTH' }, { name: '1 kvartal', value: 'ONE_QUARTER' },
{ name: '1 kvartal', value: 'ONE_QUARTER' }, { name: '1 år', value: 'ONE_YEAR' }
{ name: '1 år', value: 'ONE_YEAR' } ]
] const snackbar = ref({ active: false, color: 'success', text: '' })
const snackbar = ref({ active: false, color: 'success', text: '' })
const origin = ref('') const origin = ref('')
const fetchEvents = () => { const fetchEvents = () => {
const originsTemp = [...(origins.value || [])] const originsTemp = [...(origins.value || [])]
if (origin.value) { if (origin.value) {
originsTemp.push(origin.value) originsTemp.push(origin.value)
} }
query({ enabled.value = true
variables: { refetch({
range: range.value, range: range.value,
origins: originsTemp, origins: originsTemp,
includeOrigins: isAuthenticated.value || false includeOrigins: isAuthenticated.value || false
}
})
}
const [doToggleIgnoreBand] = useMutation(toggleIgnoreBand)
const [doToggleIgnoreDanceHall] = useMutation(toggleIgnoreDanceHall)
const [doToggleIgnoreCity] = useMutation(toggleIgnoreCity)
const [doToggleIgnoreMunicipality] = useMutation(toggleIgnoreMunicipality)
const [doToggleIgnoreState] = useMutation(toggleIgnoreState)
const toggleIgnoreSuccess = name => {
return () => {
fetchEvents()
snackbar.value.color = 'success'
snackbar.value.text = `${name} har dolts`
snackbar.value.active = true
}
}
const toggleIgnoreFailed = name => {
return () => {
snackbar.value.color = 'error'
snackbar.value.text = `${name} kunde inte döljas`
snackbar.value.active = true
}
}
const toggleIgnore = (type, name) => {
switch (type) {
case 'band':
doToggleIgnoreBand({ variables: { name } })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'danceHall':
doToggleIgnoreDanceHall({ variables: { name } })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'city':
doToggleIgnoreCity({ variables: { name } })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'municipality':
doToggleIgnoreMunicipality({ variables: { name } })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'state':
doToggleIgnoreState({ variables: { name } })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
default:
}
}
const [doSaveOrigin] = useMutation(saveOrigin)
const [doFetchAddress, { data: address }] = useLazyQuery(fetchAddress)
const fetchAddressFn = () => {
if (window.navigator) {
window.navigator.geolocation.getCurrentPosition(pos => {
doFetchAddress({
variables: {
latlng: `${pos.coords.latitude},${pos.coords.longitude}`
}
}).then(() => {
origin.value = address.value.address
})
}) })
} }
}
const saveOriginFn = o =>
doSaveOrigin({ variables: { origin: o } }).then(() => {
origin.value = ''
fetchEvents()
})
return { const { mutate: doToggleIgnoreBand } = useMutation(toggleIgnoreBand)
authLoading, const { mutate: doToggleIgnoreDanceHall } = useMutation(toggleIgnoreDanceHall)
isAuthenticated, const { mutate: doToggleIgnoreCity } = useMutation(toggleIgnoreCity)
range, const { mutate: doToggleIgnoreMunicipality } = useMutation(toggleIgnoreMunicipality)
events, const { mutate: doToggleIgnoreState } = useMutation(toggleIgnoreState)
origins,
query: fetchEvents, const toggleIgnoreSuccess = name => {
submitting, return () => {
ranges, fetchEvents()
snackbar, snackbar.value.color = 'success'
toggleIgnore, snackbar.value.text = `${name} har dolts`
origin, snackbar.value.active = true
fetchAddress: fetchAddressFn, }
saveOrigin: saveOriginFn }
const toggleIgnoreFailed = name => {
return () => {
snackbar.value.color = 'error'
snackbar.value.text = `${name} kunde inte döljas`
snackbar.value.active = true
}
}
const toggleIgnore = (type, name) => {
switch (type) {
case 'band':
doToggleIgnoreBand({ name })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'danceHall':
doToggleIgnoreDanceHall({ name })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'city':
doToggleIgnoreCity({ name })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'municipality':
doToggleIgnoreMunicipality({ name })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
case 'state':
doToggleIgnoreState({ name })
.then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed)
break
default:
}
}
const { mutate: doSaveOrigin } = useMutation(saveOrigin)
const addressEnabled = ref(false)
const { result: address, refetch: doFetchAddress } = useQuery(fetchAddress, {}, () => ({ enabled: addressEnabled.value }))
const fetchAddressFn = () => {
if (window.navigator) {
window.navigator.geolocation.getCurrentPosition(pos => {
addressEnabled.value = true
doFetchAddress({
latlng: `${pos.coords.latitude},${pos.coords.longitude}`
}).then(() => {
origin.value = address.value.address
})
})
}
}
const saveOriginFn = o =>
doSaveOrigin({ origin: o }).then(() => {
origin.value = ''
fetchEvents()
})
return {
authLoading,
isAuthenticated,
range,
events,
origins,
query: fetchEvents,
submitting,
ranges,
snackbar,
toggleIgnore,
origin,
fetchAddress: fetchAddressFn,
saveOrigin: saveOriginFn
}
} }
} }
}
</script> </script>
+13 -13
View File
@@ -69,8 +69,8 @@ import {
} from '~/utils/graph-client' } from '~/utils/graph-client'
import List from './List' import List from './List'
import { useMutation, useQuery, useResult } from '../../../plugins/apollo' import { useMutation, useQuery, useResult } from '@vue/apollo-composable'
import useAuth from '../../../plugins/auth' import { useAuth } from '../../../plugins/auth'
import { useTranslation } from '../../../plugins/i18n' import { useTranslation } from '../../../plugins/i18n'
export default { export default {
@@ -82,18 +82,18 @@ export default {
const { t } = useTranslation() const { t } = useTranslation()
setTitle(t('app.links.filters')) setTitle(t('app.links.filters'))
const { isAuthenticated } = useAuth() const { isAuthenticated } = useAuth()
const { data, loading, refetch } = useQuery(fetchFilters) const { result: data, loading, refetch } = useQuery(fetchFilters)
const bands = useResult(data, [], result => result.bands) const bands = useResult(data, [], result => result.bands)
const cities = useResult(data, [], result => result.cities) const cities = useResult(data, [], result => result.cities)
const danceHalls = useResult(data, [], result => result.danceHalls) const danceHalls = useResult(data, [], result => result.danceHalls)
const municipalities = useResult(data, [], result => result.municipalities) const municipalities = useResult(data, [], result => result.municipalities)
const states = useResult(data, [], result => result.states) const states = useResult(data, [], result => result.states)
const snackbar = ref({ active: false, color: 'success', text: '' }) const snackbar = ref({ active: false, color: 'success', text: '' })
const [doToggleIgnoreBand] = useMutation(toggleIgnoreBand) const {mutate: doToggleIgnoreBand} = useMutation(toggleIgnoreBand)
const [doToggleIgnoreDanceHall] = useMutation(toggleIgnoreDanceHall) const {mutate: doToggleIgnoreDanceHall} = useMutation(toggleIgnoreDanceHall)
const [doToggleIgnoreCity] = useMutation(toggleIgnoreCity) const {mutate: doToggleIgnoreCity} = useMutation(toggleIgnoreCity)
const [doToggleIgnoreMunicipality] = useMutation(toggleIgnoreMunicipality) const {mutate: doToggleIgnoreMunicipality} = useMutation(toggleIgnoreMunicipality)
const [doToggleIgnoreState] = useMutation(toggleIgnoreState) const {mutate: doToggleIgnoreState} = useMutation(toggleIgnoreState)
const toggleIgnoreSuccess = name => { const toggleIgnoreSuccess = name => {
return () => { return () => {
@@ -115,27 +115,27 @@ export default {
const toggleIgnore = (type, name) => { const toggleIgnore = (type, name) => {
switch (type) { switch (type) {
case 'band': case 'band':
doToggleIgnoreBand({ variables: { name } }) doToggleIgnoreBand({ name })
.then(toggleIgnoreSuccess(name)) .then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed) .catch(toggleIgnoreFailed)
break break
case 'danceHall': case 'danceHall':
doToggleIgnoreDanceHall({ variables: { name } }) doToggleIgnoreDanceHall({ name })
.then(toggleIgnoreSuccess(name)) .then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed) .catch(toggleIgnoreFailed)
break break
case 'city': case 'city':
doToggleIgnoreCity({ variables: { name } }) doToggleIgnoreCity({ name })
.then(toggleIgnoreSuccess(name)) .then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed) .catch(toggleIgnoreFailed)
break break
case 'municipality': case 'municipality':
doToggleIgnoreMunicipality({ variables: { name } }) doToggleIgnoreMunicipality({ name })
.then(toggleIgnoreSuccess(name)) .then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed) .catch(toggleIgnoreFailed)
break break
case 'state': case 'state':
doToggleIgnoreState({ variables: { name } }) doToggleIgnoreState({ name })
.then(toggleIgnoreSuccess(name)) .then(toggleIgnoreSuccess(name))
.catch(toggleIgnoreFailed) .catch(toggleIgnoreFailed)
break break
+53 -62
View File
@@ -11,10 +11,11 @@
<v-tooltip top slot="append-outer"> <v-tooltip top slot="append-outer">
<template v-slot:activator="{ on }"> <template v-slot:activator="{ on }">
<v-icon v-on="on" v-on:click="fetchAddress()" <v-icon v-on="on" v-on:click="fetchAddress()"
>mdi-crosshairs-gps</v-icon >mdi-crosshairs-gps
</v-icon
> >
</template> </template>
<span v-text="$t('origins.fetchAddress')" /> <span v-text="$t('origins.fetchAddress')"/>
</v-tooltip> </v-tooltip>
<v-tooltip top slot="prepend"> <v-tooltip top slot="prepend">
<template v-slot:activator="{ on }"> <template v-slot:activator="{ on }">
@@ -22,10 +23,11 @@
v-on="on" v-on="on"
:disabled="!origin" :disabled="!origin"
v-on:click="saveOrigin(origin)" v-on:click="saveOrigin(origin)"
>mdi-bookmark-plus-outline</v-icon >mdi-bookmark-plus-outline
</v-icon
> >
</template> </template>
<span v-text="$t('origins.save')" /> <span v-text="$t('origins.save')"/>
</v-tooltip> </v-tooltip>
</v-text-field> </v-text-field>
</v-flex> </v-flex>
@@ -36,10 +38,10 @@
<v-tooltip top slot="prepend"> <v-tooltip top slot="prepend">
<template v-slot:activator="{ on }"> <template v-slot:activator="{ on }">
<v-icon v-on="on" v-on:click="removeOrigin(origin)" <v-icon v-on="on" v-on:click="removeOrigin(origin)"
>mdi-delete-outline >mdi-delete-outline
</v-icon> </v-icon>
</template> </template>
<span v-text="$t('origins.remove')" /> <span v-text="$t('origins.remove')"/>
</v-tooltip> </v-tooltip>
<span>{{ origin }}</span> <span>{{ origin }}</span>
</v-flex> </v-flex>
@@ -57,66 +59,55 @@
</template> </template>
<script> <script>
import { ref } from '@vue/composition-api' import { ref } from '@vue/composition-api'
import { useMutations } from '@u3u/vue-hooks' import { useMutations } from '@u3u/vue-hooks'
import { import { fetchAddress, findOrigins, removeOrigin, saveOrigin } from '../../../utils/graph-client'
fetchAddress, import { useMutation, useQuery, useResult } from '@vue/apollo-composable'
findOrigins, import { useAuth } from '../../../plugins/auth'
removeOrigin, import { useTranslation } from '../../../plugins/i18n'
saveOrigin
} from '../../../utils/graph-client'
import {
useLazyQuery,
useMutation,
useQuery,
useResult
} from '../../../plugins/apollo'
import useAuth from '../../../plugins/auth'
import { useTranslation } from '../../../plugins/i18n'
export default { export default {
setup() { setup() {
const { setTitle } = useMutations(['setTitle']) const { setTitle } = useMutations(['setTitle'])
const { t } = useTranslation() const { t } = useTranslation()
setTitle(t('app.links.origins')) setTitle(t('app.links.origins'))
const { isAuthenticated } = useAuth() const { isAuthenticated } = useAuth()
const { data, loading, refetch } = useQuery(findOrigins) const { result: data, loading, refetch } = useQuery(findOrigins)
const origins = useResult(data, []) const origins = useResult(data, [])
const snackbar = ref({ active: false, color: 'success', text: '' }) const snackbar = ref({ active: false, color: 'success', text: '' })
const [doSaveOrigin] = useMutation(saveOrigin) const {mutate: doSaveOrigin} = useMutation(saveOrigin)
const [doRemoveOrigin] = useMutation(removeOrigin) const {mutate: doRemoveOrigin} = useMutation(removeOrigin)
const [doFetchAddress] = useLazyQuery(fetchAddress) const enabled = ref(false)
const origin = ref('') const { refetch: doFetchAddress } = useQuery(fetchAddress, {}, () => ({ enabled: enabled.value }))
const fetchAddressFn = () => { const origin = ref('')
if (window.navigator) { const fetchAddressFn = () => {
window.navigator.geolocation.getCurrentPosition(pos => { if (window.navigator) {
doFetchAddress({ window.navigator.geolocation.getCurrentPosition(pos => {
variables: { enabled.value = true
latlng: `${pos.coords.latitude},${pos.coords.longitude}` doFetchAddress({ latlng: `${pos.coords.latitude},${pos.coords.longitude}` })
} .then(res => {
}).then(res => { origin.value = res.address
origin.value = res.address })
}) })
}
}
const saveOriginFn = o =>
doSaveOrigin({ origin: o }).then(() => {
refetch()
origin.value = ''
}) })
const removeOriginFn = o =>
doRemoveOrigin({ origin: o }).then(() => refetch())
return {
isAuthenticated,
loading,
origins,
snackbar,
origin,
saveOrigin: saveOriginFn,
removeOrigin: removeOriginFn,
fetchAddress: fetchAddressFn
} }
} }
const saveOriginFn = o =>
doSaveOrigin({ variables: { origin: o } }).then(() => {
refetch()
origin.value = ''
})
const removeOriginFn = o =>
doRemoveOrigin({ variables: { origin: o } }).then(() => refetch())
return {
isAuthenticated,
loading,
origins,
snackbar,
origin,
saveOrigin: saveOriginFn,
removeOrigin: removeOriginFn,
fetchAddress: fetchAddressFn
}
} }
}
</script> </script>
+3 -3
View File
@@ -69,11 +69,11 @@
</v-list-item> </v-list-item>
</v-toolbar-items> </v-toolbar-items>
</v-app-bar> </v-app-bar>
<v-content> <v-main>
<v-container fluid v-if="!loading"> <v-container fluid v-if="!loading">
<nuxt /> <nuxt />
</v-container> </v-container>
</v-content> </v-main>
</themed> </themed>
</v-app> </v-app>
</template> </template>
@@ -100,7 +100,7 @@ import dayjs from 'dayjs'
import sv from 'dayjs/locale/sv' import sv from 'dayjs/locale/sv'
import { setDarkMode } from '../utils/localStorage' import { setDarkMode } from '../utils/localStorage'
import Themed from './components/themed' import Themed from './components/themed'
import useAuth from '../plugins/auth' import { useAuth } from '../plugins/auth'
export default { export default {
components: { components: {
+1 -1
View File
@@ -1,4 +1,4 @@
import useAuth from '../plugins/auth' import { useAuth } from '../plugins/auth'
export default async ({ app: { router } }) => { export default async ({ app: { router } }) => {
const onRedirectCallback = appState => { const onRedirectCallback = appState => {
+4
View File
@@ -18,6 +18,9 @@ export default {
} }
} }
}, },
buildModules: [
'nuxt-composition-api'
],
css: ['vuetify/dist/vuetify.css', '~/assets/scss/global.scss'], css: ['vuetify/dist/vuetify.css', '~/assets/scss/global.scss'],
env: { env: {
graphqlApi: process.env.GRAPHQL_API graphqlApi: process.env.GRAPHQL_API
@@ -100,6 +103,7 @@ export default {
['@nuxtjs/moment', { locales: ['sv'], defaultLocale: 'sv' }] ['@nuxtjs/moment', { locales: ['sv'], defaultLocale: 'sv' }]
], ],
plugins: [ plugins: [
'~/plugins/apollo',
'~/plugins/composition', '~/plugins/composition',
'~/plugins/hooks', '~/plugins/hooks',
'~/plugins/i18n', '~/plugins/i18n',
+3 -1
View File
@@ -12,7 +12,8 @@
"@nuxtjs/sentry": "^4.0.0", "@nuxtjs/sentry": "^4.0.0",
"@nuxtjs/vuetify": "^1.9.0", "@nuxtjs/vuetify": "^1.9.0",
"@u3u/vue-hooks": "^2.0.1", "@u3u/vue-hooks": "^2.0.1",
"@vue/composition-api": "^0.3.4", "@vue/apollo-composable": "^4.0.0-alpha.8",
"@vue/composition-api": "^0.5.0",
"apollo": "^2.17.4", "apollo": "^2.17.4",
"apollo-cache-inmemory": "^1.6.3", "apollo-cache-inmemory": "^1.6.3",
"apollo-client": "^2.6.4", "apollo-client": "^2.6.4",
@@ -27,6 +28,7 @@
"moment": "^2.24.0", "moment": "^2.24.0",
"node-sass": "^4.12.0", "node-sass": "^4.12.0",
"nuxt": "^2.8.1", "nuxt": "^2.8.1",
"nuxt-composition-api": "^0.9.3",
"nuxt-i18n": "^6.0.1", "nuxt-i18n": "^6.0.1",
"sass-loader": "^7.0.3", "sass-loader": "^7.0.3",
"snyk": "^1.316.1", "snyk": "^1.316.1",
+21 -137
View File
@@ -1,30 +1,27 @@
/* eslint no-shadow: ["error", { "allow": ["options"] }] */
import { ApolloClient } from 'apollo-client' import { ApolloClient } from 'apollo-client'
import { import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
InMemoryCache,
IntrospectionFragmentMatcher
} from 'apollo-cache-inmemory'
import { createHttpLink } from 'apollo-link-http' import { createHttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context' import { setContext } from 'apollo-link-context'
import { computed, reactive, toRefs } from '@vue/composition-api' import { useAuth } from './auth'
import useAuth from './auth' import { provide } from '@vue/composition-api'
import introspectionQueryResultData from '../fragmentTypes.json' import introspectionQueryResultData from '../fragmentTypes.json'
import { onGlobalSetup } from 'nuxt-composition-api'
import { DefaultApolloClient } from '@vue/apollo-composable'
import Vue from 'vue'
const apiUrl = process.env.graphqlApi || '/query'
const fragmentMatcher = new IntrospectionFragmentMatcher({ const fragmentMatcher = new IntrospectionFragmentMatcher({
introspectionQueryResultData introspectionQueryResultData
}) })
let instance = null
const apiUrl = process.env.graphqlApi || '/query'
const cache = new InMemoryCache({ fragmentMatcher }) const cache = new InMemoryCache({ fragmentMatcher })
const httpLink = createHttpLink({ const httpLink = createHttpLink({
uri: apiUrl uri: apiUrl
}) })
const getToken = async options => { const getToken = async (options) => {
const { getTokenSilently } = useAuth() const { getTokenSilently } = useAuth()
return getTokenSilently.value(options) return getTokenSilently.value(options)
} }
@@ -38,137 +35,24 @@ const authLink = setContext(async (_, { headers }) => {
})) }))
}) })
console.log('Setting up Apollo') const link = authLink.concat(httpLink)
instance = new ApolloClient({
link: authLink.concat(httpLink), const instance = new ApolloClient({
connectToDevTools: true,
link,
cache, cache,
defaultOptions: { defaultOptions: {
query: {
fetchPolicy: 'cache-and-network'
},
watchQuery: { watchQuery: {
fetchPolicy: 'cache-and-network' fetchPolicy: 'cache-and-network'
} }
} }
}) })
const merge = (target, ...source) => { Vue.use(() => {
const sources = source instanceof Array ? source : [source] onGlobalSetup(() => {
return sources.reduce((acc, src) => { provide(DefaultApolloClient, instance)
Object.keys(src).forEach(key => {
if (src[key] instanceof Object)
Object.assign(src[key], merge(acc[key], src[key]))
})
return Object.assign(acc, src)
}, target || {})
}
export const useMutation = (mutation, options) => {
const opts = options
const out = reactive({
data: {},
error: null,
loading: false
}) })
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)
})
})
return [doMutate, toRefs(out)]
}
export const useLazyQuery = (query, options) => {
const opts = options
let watchedQuery = null
const out = reactive({
data: {},
error: null,
loading: false
})
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()
}
}
return [
doQuery,
{
...toRefs(out),
refetch,
startPolling,
stopPolling
}
]
}
export const useQuery = (query, options) => {
const [doQuery, out] = useLazyQuery(query, options)
doQuery()
return out
}
export const useResult = (result, defaultValue, pick) => {
return computed(() => {
const { value } = result
if (value) {
if (pick) {
try {
return pick(value)
} catch (e) {
// Silent error
return defaultValue
}
} else {
const keys = Object.keys(value)
if (keys.length === 1) {
// Automatically take the only key in result data
return value[keys[0]]
}
// Return entire result data
return value
}
} else {
return defaultValue
}
})
}
+1 -1
View File
@@ -10,7 +10,7 @@ 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' const domain = params.get('domain') || 'unbound.eu.auth0.com'
export default (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => { export const useAuth = (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
if (instance) { if (instance) {
return toRefs(instance) return toRefs(instance)
} }
+2774 -2071
View File
File diff suppressed because it is too large Load Diff