chore: make auth and apollo a bit more reactive
This commit is contained in:
@@ -0,0 +1,6 @@
|
|||||||
|
schema: ./schema.graphql
|
||||||
|
overwrite: true
|
||||||
|
generates:
|
||||||
|
./fragmentTypes.json:
|
||||||
|
plugins:
|
||||||
|
- fragment-matcher
|
||||||
@@ -70,7 +70,7 @@
|
|||||||
>{{ event.danceHall.state }}</v-flex
|
>{{ event.danceHall.state }}</v-flex
|
||||||
>
|
>
|
||||||
</v-layout>
|
</v-layout>
|
||||||
<v-layout row wrap v-for="distance in event.distances" :key="distance">
|
<v-layout row wrap v-for="distance in event.distances" :key="distance.origin">
|
||||||
<v-flex xs12 sm6>
|
<v-flex xs12 sm6>
|
||||||
<v-icon>mdi-home</v-icon>
|
<v-icon>mdi-home</v-icon>
|
||||||
<span
|
<span
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<div v-if="events && events.events">
|
<div>
|
||||||
<v-layout row wrap v-for="event in events.events" :key="event.id">
|
<v-layout row wrap v-for="event in events" :key="event.id">
|
||||||
<v-flex xs12>
|
<v-flex xs12>
|
||||||
<Event
|
<Event
|
||||||
:event="event"
|
:event="event"
|
||||||
@@ -29,7 +29,7 @@ export default {
|
|||||||
required: true
|
required: true
|
||||||
},
|
},
|
||||||
events: {
|
events: {
|
||||||
type: Object,
|
type: Array,
|
||||||
required: true
|
required: true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@
|
|||||||
</v-flex>
|
</v-flex>
|
||||||
</v-layout>
|
</v-layout>
|
||||||
<list
|
<list
|
||||||
:events="data"
|
:events="events || []"
|
||||||
:has-user="isAuthenticated"
|
:has-user="isAuthenticated"
|
||||||
:toggleIgnore="toggleIgnore"
|
:toggleIgnore="toggleIgnore"
|
||||||
/>
|
/>
|
||||||
@@ -79,10 +79,10 @@
|
|||||||
<script>
|
<script>
|
||||||
import { useRouter, useMutations } from '@u3u/vue-hooks'
|
import { useRouter, useMutations } 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 } from '../../../plugins/apollo'
|
import { useLazyQuery, useMutation, useResult } from '../../../plugins/apollo'
|
||||||
import {
|
import {
|
||||||
fetchAddress,
|
fetchAddress,
|
||||||
findEvents,
|
findEvents,
|
||||||
@@ -110,6 +110,8 @@ export default {
|
|||||||
set: value => router.push(`/?range=${value}`)
|
set: value => router.push(`/?range=${value}`)
|
||||||
})
|
})
|
||||||
const [query, { data }] = useLazyQuery(findEvents)
|
const [query, { data }] = useLazyQuery(findEvents)
|
||||||
|
const events = useResult(data, [], data => data.events)
|
||||||
|
const origins = useResult(data, [], data => data.origins)
|
||||||
watch(
|
watch(
|
||||||
() => range.value,
|
() => range.value,
|
||||||
r => {
|
r => {
|
||||||
@@ -134,14 +136,14 @@ export default {
|
|||||||
|
|
||||||
const origin = ref('')
|
const origin = ref('')
|
||||||
const fetchEvents = () => {
|
const fetchEvents = () => {
|
||||||
const origins = [...(data.value.origins || [])]
|
const originsTemp = [...(origins.value || [])]
|
||||||
if (origin.value) {
|
if (origin.value) {
|
||||||
origins.push(origin.value)
|
originsTemp.push(origin.value)
|
||||||
}
|
}
|
||||||
query({
|
query({
|
||||||
variables: {
|
variables: {
|
||||||
range: range.value,
|
range: range.value,
|
||||||
origins,
|
origins: originsTemp,
|
||||||
includeOrigins: isAuthenticated.value || false
|
includeOrigins: isAuthenticated.value || false
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -226,7 +228,8 @@ export default {
|
|||||||
authLoading,
|
authLoading,
|
||||||
isAuthenticated,
|
isAuthenticated,
|
||||||
range,
|
range,
|
||||||
data,
|
events,
|
||||||
|
origins,
|
||||||
query: fetchEvents,
|
query: fetchEvents,
|
||||||
submitting,
|
submitting,
|
||||||
ranges,
|
ranges,
|
||||||
@@ -239,53 +242,3 @@ export default {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style lang="scss" scoped>
|
|
||||||
.left {
|
|
||||||
padding: 1.5rem 1rem;
|
|
||||||
|
|
||||||
> * {
|
|
||||||
margin-bottom: 1.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
hr {
|
|
||||||
border: 0;
|
|
||||||
border-top: 1px solid #eaeaea;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.left,
|
|
||||||
.right {
|
|
||||||
height: 100vh;
|
|
||||||
overflow: scroll;
|
|
||||||
overflow-x: hidden;
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media screen and(max-width: 1200px) {
|
|
||||||
.left {
|
|
||||||
width: 40vw;
|
|
||||||
}
|
|
||||||
.right {
|
|
||||||
width: 60vw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media screen and(max-width: 1024px) {
|
|
||||||
.left {
|
|
||||||
width: 50vw;
|
|
||||||
}
|
|
||||||
.right {
|
|
||||||
width: 50vw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media screen and(min-width: 1200px) {
|
|
||||||
.left {
|
|
||||||
width: 35vw;
|
|
||||||
}
|
|
||||||
.right {
|
|
||||||
width: 65vw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|||||||
@@ -5,43 +5,38 @@
|
|||||||
<v-flex xs12>
|
<v-flex xs12>
|
||||||
<v-card>
|
<v-card>
|
||||||
<v-container fluid grid-list-md>
|
<v-container fluid grid-list-md>
|
||||||
<v-layout row wrap v-if="!loading && data">
|
<v-layout row wrap>
|
||||||
<list
|
<list
|
||||||
:model="data.bands"
|
:model="bands || []"
|
||||||
title="filters.band"
|
title="filters.band"
|
||||||
type="band"
|
type="band"
|
||||||
:toggleIgnore="toggleIgnore"
|
:toggleIgnore="toggleIgnore"
|
||||||
v-if="data.bands"
|
|
||||||
/>
|
/>
|
||||||
<v-flex xs12 sm6 md4 lg3>
|
<v-flex xs12 sm6 md4 lg3>
|
||||||
<v-layout column>
|
<v-layout column>
|
||||||
<list
|
<list
|
||||||
:model="data.states"
|
:model="states || []"
|
||||||
title="filters.state"
|
title="filters.state"
|
||||||
type="state"
|
type="state"
|
||||||
:toggleIgnore="toggleIgnore"
|
:toggleIgnore="toggleIgnore"
|
||||||
v-if="data.states"
|
|
||||||
/>
|
/>
|
||||||
<list
|
<list
|
||||||
:model="data.municipalities"
|
:model="municipalities || []"
|
||||||
title="filters.municipality"
|
title="filters.municipality"
|
||||||
type="municipality"
|
type="municipality"
|
||||||
:toggleIgnore="toggleIgnore"
|
:toggleIgnore="toggleIgnore"
|
||||||
v-if="data.municipalities"
|
|
||||||
/>
|
/>
|
||||||
<list
|
<list
|
||||||
:model="data.cities"
|
:model="cities || []"
|
||||||
title="filters.city"
|
title="filters.city"
|
||||||
type="city"
|
type="city"
|
||||||
:toggleIgnore="toggleIgnore"
|
:toggleIgnore="toggleIgnore"
|
||||||
v-if="data.cities"
|
|
||||||
/>
|
/>
|
||||||
<list
|
<list
|
||||||
:model="data.danceHalls"
|
:model="danceHalls || []"
|
||||||
title="filters.hall"
|
title="filters.hall"
|
||||||
type="danceHall"
|
type="danceHall"
|
||||||
:toggleIgnore="toggleIgnore"
|
:toggleIgnore="toggleIgnore"
|
||||||
v-if="data.danceHalls"
|
|
||||||
/>
|
/>
|
||||||
</v-layout>
|
</v-layout>
|
||||||
</v-flex>
|
</v-flex>
|
||||||
@@ -74,8 +69,8 @@ import {
|
|||||||
} from '~/utils/graph-client'
|
} from '~/utils/graph-client'
|
||||||
|
|
||||||
import List from './List'
|
import List from './List'
|
||||||
import { useMutation, useQuery } from '../../../plugins/apollo'
|
import { useMutation, useQuery, useResult } from '../../../plugins/apollo'
|
||||||
import useAuth from '../../../plugins/auth'
|
import { useAuth } from '../../../plugins/auth'
|
||||||
import { useTranslation } from '../../../plugins/i18n'
|
import { useTranslation } from '../../../plugins/i18n'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
@@ -88,6 +83,11 @@ export default {
|
|||||||
setTitle(t('app.links.filters'))
|
setTitle(t('app.links.filters'))
|
||||||
const { isAuthenticated } = useAuth()
|
const { isAuthenticated } = useAuth()
|
||||||
const { data, loading, refetch } = useQuery(fetchFilters)
|
const { data, loading, refetch } = useQuery(fetchFilters)
|
||||||
|
const bands = useResult(data, [], data => data.bands)
|
||||||
|
const cities = useResult(data, [], data => data.cities)
|
||||||
|
const danceHalls = useResult(data, [], data => data.danceHalls)
|
||||||
|
const municipalities = useResult(data, [], data => data.municipalities)
|
||||||
|
const states = useResult(data, [], data => data.states)
|
||||||
const snackbar = ref({ active: false, color: 'success', text: '' })
|
const snackbar = ref({ active: false, color: 'success', text: '' })
|
||||||
const [doToggleIgnoreBand] = useMutation(toggleIgnoreBand)
|
const [doToggleIgnoreBand] = useMutation(toggleIgnoreBand)
|
||||||
const [doToggleIgnoreDanceHall] = useMutation(toggleIgnoreDanceHall)
|
const [doToggleIgnoreDanceHall] = useMutation(toggleIgnoreDanceHall)
|
||||||
@@ -97,7 +97,7 @@ export default {
|
|||||||
|
|
||||||
const toggleIgnoreSuccess = name => {
|
const toggleIgnoreSuccess = name => {
|
||||||
return () => {
|
return () => {
|
||||||
refetch.value()
|
refetch()
|
||||||
snackbar.value.color = 'success'
|
snackbar.value.color = 'success'
|
||||||
snackbar.value.text = t('filters.success', { name })
|
snackbar.value.text = t('filters.success', { name })
|
||||||
snackbar.value.active = true
|
snackbar.value.active = true
|
||||||
@@ -146,7 +146,11 @@ export default {
|
|||||||
return {
|
return {
|
||||||
isAuthenticated,
|
isAuthenticated,
|
||||||
loading,
|
loading,
|
||||||
data,
|
bands,
|
||||||
|
danceHalls,
|
||||||
|
cities,
|
||||||
|
municipalities,
|
||||||
|
states,
|
||||||
snackbar,
|
snackbar,
|
||||||
toggleIgnore
|
toggleIgnore
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,8 +30,8 @@
|
|||||||
</v-text-field>
|
</v-text-field>
|
||||||
</v-flex>
|
</v-flex>
|
||||||
</v-layout>
|
</v-layout>
|
||||||
<template v-if="data && data.origins">
|
<template>
|
||||||
<v-layout row wrap v-for="origin in data.origins" :key="origin">
|
<v-layout row wrap v-for="origin in origins" :key="origin">
|
||||||
<v-flex xs12>
|
<v-flex xs12>
|
||||||
<v-tooltip top slot="prepend">
|
<v-tooltip top slot="prepend">
|
||||||
<template v-slot:activator="{ on }">
|
<template v-slot:activator="{ on }">
|
||||||
@@ -65,8 +65,8 @@ import {
|
|||||||
removeOrigin,
|
removeOrigin,
|
||||||
saveOrigin
|
saveOrigin
|
||||||
} from '../../../utils/graph-client'
|
} from '../../../utils/graph-client'
|
||||||
import { useLazyQuery, useMutation, useQuery } from '../../../plugins/apollo'
|
import { useLazyQuery, useMutation, useQuery, useResult } from '../../../plugins/apollo'
|
||||||
import useAuth from '../../../plugins/auth'
|
import { useAuth } from '../../../plugins/auth'
|
||||||
import { useTranslation } from '../../../plugins/i18n'
|
import { useTranslation } from '../../../plugins/i18n'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
@@ -76,10 +76,11 @@ export default {
|
|||||||
setTitle(t('app.links.origins'))
|
setTitle(t('app.links.origins'))
|
||||||
const { isAuthenticated } = useAuth()
|
const { isAuthenticated } = useAuth()
|
||||||
const { data, loading, refetch } = useQuery(findOrigins)
|
const { data, loading, refetch } = useQuery(findOrigins)
|
||||||
|
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 [doSaveOrigin] = useMutation(saveOrigin)
|
||||||
const [doRemoveOrigin] = useMutation(removeOrigin)
|
const [doRemoveOrigin] = useMutation(removeOrigin)
|
||||||
const [doFetchAddress, { data: address }] = useLazyQuery(fetchAddress)
|
const [doFetchAddress] = useLazyQuery(fetchAddress)
|
||||||
const origin = ref('')
|
const origin = ref('')
|
||||||
const fetchAddressFn = () => {
|
const fetchAddressFn = () => {
|
||||||
if (window.navigator) {
|
if (window.navigator) {
|
||||||
@@ -88,23 +89,23 @@ export default {
|
|||||||
variables: {
|
variables: {
|
||||||
latlng: `${pos.coords.latitude},${pos.coords.longitude}`
|
latlng: `${pos.coords.latitude},${pos.coords.longitude}`
|
||||||
}
|
}
|
||||||
}).then(() => {
|
}).then(res => {
|
||||||
origin.value = address.value.address
|
origin.value = res.address
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const saveOriginFn = o =>
|
const saveOriginFn = o =>
|
||||||
doSaveOrigin({ variables: { origin: o } }).then(() => {
|
doSaveOrigin({ variables: { origin: o } }).then(() => {
|
||||||
refetch.value()
|
refetch()
|
||||||
origin.value = ''
|
origin.value = ''
|
||||||
})
|
})
|
||||||
const removeOriginFn = o =>
|
const removeOriginFn = o =>
|
||||||
doRemoveOrigin({ variables: { origin: o } }).then(() => refetch.value())
|
doRemoveOrigin({ variables: { origin: o } }).then(() => refetch())
|
||||||
return {
|
return {
|
||||||
isAuthenticated,
|
isAuthenticated,
|
||||||
loading,
|
loading,
|
||||||
data,
|
origins,
|
||||||
snackbar,
|
snackbar,
|
||||||
origin,
|
origin,
|
||||||
saveOrigin: saveOriginFn,
|
saveOrigin: saveOriginFn,
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"__schema": {
|
||||||
|
"types": []
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -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: {
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { useAuth } from '../plugins/auth'
|
||||||
|
|
||||||
|
export default async ({app: { router }}) => {
|
||||||
|
const onRedirectCallback = appState => {
|
||||||
|
router.push(
|
||||||
|
appState && appState.targetUrl
|
||||||
|
? appState.targetUrl
|
||||||
|
: window.location.pathname
|
||||||
|
)
|
||||||
|
}
|
||||||
|
useAuth(onRedirectCallback)
|
||||||
|
}
|
||||||
+35
-30
@@ -2,10 +2,26 @@ import translations from './translations'
|
|||||||
import numberFormats from './translations/numberFormats'
|
import numberFormats from './translations/numberFormats'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
|
build: {
|
||||||
|
babel: {
|
||||||
|
presets({ isServer }) {
|
||||||
|
return [
|
||||||
|
[
|
||||||
|
require.resolve('@nuxt/babel-preset-app'),
|
||||||
|
// require.resolve('@nuxt/babel-preset-app-edge'), // For nuxt-edge users
|
||||||
|
{
|
||||||
|
buildTarget: isServer ? 'server' : 'client',
|
||||||
|
corejs: { version: 3 }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
css: ['vuetify/dist/vuetify.css', '~/assets/scss/global.scss'],
|
||||||
env: {
|
env: {
|
||||||
graphqlApi: process.env.GRAPHQL_API
|
graphqlApi: process.env.GRAPHQL_API
|
||||||
},
|
},
|
||||||
mode: 'spa',
|
|
||||||
head: {
|
head: {
|
||||||
link: [
|
link: [
|
||||||
{
|
{
|
||||||
@@ -51,12 +67,6 @@ export default {
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
modules: [
|
|
||||||
'nuxt-i18n',
|
|
||||||
'@nuxtjs/sentry',
|
|
||||||
'@nuxtjs/vuetify',
|
|
||||||
['@nuxtjs/moment', { locales: ['sv'], defaultLocale: 'sv' }]
|
|
||||||
],
|
|
||||||
i18n: {
|
i18n: {
|
||||||
strategy: 'prefix_and_default',
|
strategy: 'prefix_and_default',
|
||||||
detectBrowserLanguage: {
|
detectBrowserLanguage: {
|
||||||
@@ -82,6 +92,24 @@ export default {
|
|||||||
numberFormats
|
numberFormats
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
mode: 'spa',
|
||||||
|
modules: [
|
||||||
|
'nuxt-i18n',
|
||||||
|
'@nuxtjs/sentry',
|
||||||
|
'@nuxtjs/vuetify',
|
||||||
|
['@nuxtjs/moment', { locales: ['sv'], defaultLocale: 'sv' }]
|
||||||
|
],
|
||||||
|
plugins: [
|
||||||
|
'~/plugins/composition',
|
||||||
|
'~/plugins/hooks',
|
||||||
|
'~/plugins/i18n',
|
||||||
|
'~/plugins/vue-numeral-filter.js'
|
||||||
|
],
|
||||||
|
router: {
|
||||||
|
middleware: [
|
||||||
|
'auth'
|
||||||
|
],
|
||||||
|
},
|
||||||
sentry: {
|
sentry: {
|
||||||
dsn: 'https://da2e8d42185a4013909d49955432a116@sentry.io/5187660',
|
dsn: 'https://da2e8d42185a4013909d49955432a116@sentry.io/5187660',
|
||||||
config: {}, // Additional config
|
config: {}, // Additional config
|
||||||
@@ -89,27 +117,4 @@ export default {
|
|||||||
vuetify: {
|
vuetify: {
|
||||||
optionsPath: './vuetify.options.js'
|
optionsPath: './vuetify.options.js'
|
||||||
},
|
},
|
||||||
css: ['vuetify/dist/vuetify.css', '~/assets/scss/global.scss'],
|
|
||||||
plugins: [
|
|
||||||
'~/plugins/composition',
|
|
||||||
'~/plugins/hooks',
|
|
||||||
'~/plugins/i18n',
|
|
||||||
'~/plugins/vue-numeral-filter.js'
|
|
||||||
],
|
|
||||||
build: {
|
|
||||||
babel: {
|
|
||||||
presets({ isServer }) {
|
|
||||||
return [
|
|
||||||
[
|
|
||||||
require.resolve('@nuxt/babel-preset-app'),
|
|
||||||
// require.resolve('@nuxt/babel-preset-app-edge'), // For nuxt-edge users
|
|
||||||
{
|
|
||||||
buildTarget: isServer ? 'server' : 'client',
|
|
||||||
corejs: { version: 3 }
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@
|
|||||||
"build": "nuxt build",
|
"build": "nuxt build",
|
||||||
"generate": "nuxt generate",
|
"generate": "nuxt generate",
|
||||||
"lint": "eslint --quiet --fix --ext .js,.vue --ignore-path .gitignore .",
|
"lint": "eslint --quiet --fix --ext .js,.vue --ignore-path .gitignore .",
|
||||||
|
"generate-gql": "graphql-codegen",
|
||||||
"precommit": "yarn lint",
|
"precommit": "yarn lint",
|
||||||
"prepush": "yarn test",
|
"prepush": "yarn test",
|
||||||
"start": "node server/index.js",
|
"start": "node server/index.js",
|
||||||
@@ -50,6 +51,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/runtime-corejs3": "^7.8.3",
|
"@babel/runtime-corejs3": "^7.8.3",
|
||||||
|
"@graphql-codegen/cli": "^1.13.1",
|
||||||
|
"@graphql-codegen/fragment-matcher": "^1.13.1",
|
||||||
"babel-eslint": "^10.0.3",
|
"babel-eslint": "^10.0.3",
|
||||||
"cli-engine": "^4.7.6",
|
"cli-engine": "^4.7.6",
|
||||||
"cypress": "^3.1.0",
|
"cypress": "^3.1.0",
|
||||||
|
|||||||
+107
-111
@@ -1,39 +1,43 @@
|
|||||||
import { ApolloClient } from 'apollo-client'
|
import { ApolloClient } from 'apollo-client'
|
||||||
|
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
|
||||||
import { createHttpLink } from 'apollo-link-http'
|
import { createHttpLink } from 'apollo-link-http'
|
||||||
import { InMemoryCache } from 'apollo-cache-inmemory'
|
|
||||||
import { setContext } from 'apollo-link-context'
|
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
|
let instance = null
|
||||||
|
|
||||||
const apiUrl = process.env.graphqlApi || '/query'
|
const apiUrl = process.env.graphqlApi || '/query'
|
||||||
|
|
||||||
|
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, isAuthenticated } = useAuth()
|
const { getTokenSilently } = useAuth()
|
||||||
if (isAuthenticated.value) {
|
return getTokenSilently.value(options)
|
||||||
return getTokenSilently.value(options)
|
|
||||||
}
|
|
||||||
return options
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const authLink = setContext(async (_, { headers }) => {
|
const authLink = setContext(async (_, { headers }) => {
|
||||||
const token = await getToken()
|
return getToken().then(token => ({
|
||||||
return {
|
|
||||||
headers: {
|
headers: {
|
||||||
...headers,
|
...headers,
|
||||||
authorization: token ? `Bearer ${token}` : ''
|
authorization: token ? `Bearer ${token}` : ''
|
||||||
}
|
}
|
||||||
}
|
}))
|
||||||
})
|
})
|
||||||
|
|
||||||
const client = new ApolloClient({
|
console.log('Setting up Apollo')
|
||||||
|
instance = new ApolloClient({
|
||||||
link: authLink.concat(httpLink),
|
link: authLink.concat(httpLink),
|
||||||
cache: new InMemoryCache(),
|
cache,
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
watchQuery: {
|
watchQuery: {
|
||||||
fetchPolicy: 'cache-and-network'
|
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) => {
|
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({
|
const out = reactive({
|
||||||
data: {},
|
data: {},
|
||||||
error: null,
|
error: null,
|
||||||
loading: false
|
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)]
|
return [doMutate, toRefs(out)]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useLazyQuery = (query, options) => {
|
export const useLazyQuery = (query, options) => {
|
||||||
|
const opts = options
|
||||||
let watchedQuery = null
|
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({
|
const out = reactive({
|
||||||
data: {},
|
data: {},
|
||||||
error: null,
|
error: null,
|
||||||
loading: false
|
loading: false
|
||||||
})
|
})
|
||||||
const doQuery = queryOptions =>
|
return [doQuery, {
|
||||||
new Promise((resolve, reject) => {
|
...toRefs(out),
|
||||||
out.loading = true
|
refetch,
|
||||||
const effectiveOptions = {
|
startPolling,
|
||||||
query,
|
stopPolling
|
||||||
...(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) => {
|
export const useQuery = (query, options) => {
|
||||||
@@ -122,44 +133,29 @@ export const useQuery = (query, options) => {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// import { execute, makePromise, ApolloLink, Observable } from 'apollo-link';
|
export const useResult = (result, defaultValue, pick) => {
|
||||||
// import { HttpLink } from 'apollo-link-http';
|
return computed(() => {
|
||||||
// const { includeCredentials } = require('./middleware');
|
const value = result.value
|
||||||
// import { onError } from 'apollo-link-error';
|
if (value) {
|
||||||
//
|
if (pick) {
|
||||||
// const defaultGraphUri = process.env.graphqlApi || 'https://shiny-gateway.unbound.se';
|
try {
|
||||||
// const httpLink = new HttpLink({ uri: defaultGraphUri, fetch: includeCredentials, credentials: 'same-origin' });
|
return pick(value)
|
||||||
// const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
|
} catch (e) {
|
||||||
// if (graphQLErrors) {
|
// Silent error
|
||||||
// console.log('GraphQL errors:', graphQLErrors);
|
}
|
||||||
// // for (let err of graphQLErrors) {
|
|
||||||
// // switch (err.extensions.code) {
|
} else {
|
||||||
// // case 'UNAUTHENTICATED':
|
const keys = Object.keys(value)
|
||||||
// // // error code is set to UNAUTHENTICATED
|
if (keys.length === 1) {
|
||||||
// // // when AuthenticationError thrown in resolver
|
// Automatically take the only key in result data
|
||||||
// //
|
return value[keys[0]]
|
||||||
// // // modify the operation context with a new token
|
} else {
|
||||||
// // }
|
// Return entire result data
|
||||||
// // }
|
return value
|
||||||
// }
|
}
|
||||||
// if (networkError) {
|
}
|
||||||
// if (networkError.statusCode === 401) {
|
} else {
|
||||||
// return new Observable(observer => {
|
return defaultValue
|
||||||
// // 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)
|
|
||||||
// // });
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// );
|
|
||||||
|
|||||||
+54
-43
@@ -7,10 +7,10 @@ const DEFAULT_REDIRECT_CALLBACK = () =>
|
|||||||
|
|
||||||
let instance
|
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)
|
||||||
}
|
}
|
||||||
@@ -34,23 +34,23 @@ export default (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
|
|||||||
this.popupOpen = true
|
this.popupOpen = true
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await instance.auth0Client.loginWithPopup(o)
|
await instance.auth0Client.then(client => client.loginWithPopup(o))
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// eslint-disable-next-line
|
// eslint-disable-next-line
|
||||||
console.error(e);
|
console.error(e)
|
||||||
} finally {
|
} finally {
|
||||||
instance.popupOpen = false
|
instance.popupOpen = false
|
||||||
}
|
}
|
||||||
|
|
||||||
instance.user = await instance.auth0Client.getUser()
|
instance.user = await instance.auth0Client.then(client => client.getUser())
|
||||||
instance.isAuthenticated = true
|
instance.isAuthenticated = true
|
||||||
},
|
},
|
||||||
/** Handles the callback when logging in using a redirect */
|
/** Handles the callback when logging in using a redirect */
|
||||||
handleRedirectCallback: async () => {
|
handleRedirectCallback: async () => {
|
||||||
instance.loading = true
|
instance.loading = true
|
||||||
try {
|
try {
|
||||||
await instance.auth0Client.handleRedirectCallback()
|
await instance.auth0Client.then(client => client.handleRedirectCallback())
|
||||||
instance.user = await instance.auth0Client.getUser()
|
instance.user = await instance.auth0Client.then(client => client.getUser())
|
||||||
instance.isAuthenticated = true
|
instance.isAuthenticated = true
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
instance.error = e
|
instance.error = e
|
||||||
@@ -60,62 +60,73 @@ export default (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
|
|||||||
},
|
},
|
||||||
/** Authenticates the user using the redirect method */
|
/** Authenticates the user using the redirect method */
|
||||||
loginWithRedirect: o => {
|
loginWithRedirect: o => {
|
||||||
return instance.auth0Client.loginWithRedirect(o)
|
return instance.auth0Client.then(client => client.loginWithRedirect(o))
|
||||||
},
|
},
|
||||||
/** Returns all the claims present in the ID token */
|
/** Returns all the claims present in the ID token */
|
||||||
getIdTokenClaims: o => {
|
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 */
|
/** Returns the access token. If the token is invalid or missing, a new one is retrieved */
|
||||||
getTokenSilently: o => {
|
getTokenSilently: o => {
|
||||||
return instance.auth0Client.getTokenSilently(o)
|
return instance.auth0Client.then(client => {
|
||||||
|
return client.getTokenSilently(o)
|
||||||
|
})
|
||||||
},
|
},
|
||||||
/** Gets the access token using a popup window */
|
/** Gets the access token using a popup window */
|
||||||
getTokenWithPopup: o => {
|
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 */
|
/** Logs the user out and removes their session on the authorization server */
|
||||||
logout: o => {
|
logout: o => {
|
||||||
return instance.auth0Client.logout(o)
|
return instance.auth0Client.then(client => client.logout(o))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
const fetchUser = () => {
|
const fetchUser = () => {
|
||||||
instance.auth0Client.isAuthenticated().then(a => {
|
instance.auth0Client
|
||||||
instance.isAuthenticated = a
|
.then(client => client.isAuthenticated())
|
||||||
instance.auth0Client.getUser().then(u => {
|
.then(a => {
|
||||||
instance.user = u
|
instance.isAuthenticated = a
|
||||||
instance.loading = false
|
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
|
// Create a new instance of the SDK client using members of the given options object
|
||||||
createAuth0Client(options).then(client => {
|
instance.auth0Client = createAuth0Client(options)
|
||||||
instance.loading = true
|
instance.auth0Client
|
||||||
instance.auth0Client = client
|
.then(client => {
|
||||||
try {
|
instance.loading = true
|
||||||
// If the user is returning to the app after authentication..
|
// instance.auth0Client = client
|
||||||
if (
|
try {
|
||||||
window.location.search.includes('code=') &&
|
// If the user is returning to the app after authentication..
|
||||||
window.location.search.includes('state=')
|
if (
|
||||||
) {
|
window.location.search.includes('code=') &&
|
||||||
// handle the redirect and retrieve tokens
|
window.location.search.includes('state=')
|
||||||
instance.auth0Client.handleRedirectCallback().then(appState => {
|
) {
|
||||||
// Notify subscribers that the redirect callback has happened, passing the appState
|
console.log('location search', window.location.search)
|
||||||
// (useful for retrieving any pre-authentication state)
|
// handle the redirect and retrieve tokens
|
||||||
onRedirectCallback(appState)
|
client.handleRedirectCallback()
|
||||||
// Initialize our internal authentication state
|
.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()
|
fetchUser()
|
||||||
})
|
}
|
||||||
} else {
|
} catch (e) {
|
||||||
fetchUser()
|
instance.error = e
|
||||||
|
} finally {
|
||||||
|
instance.loading = false
|
||||||
}
|
}
|
||||||
} catch (e) {
|
})
|
||||||
instance.error = e
|
|
||||||
} finally {
|
|
||||||
instance.loading = false
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return toRefs(instance)
|
return toRefs(instance)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user