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
+6
View File
@@ -0,0 +1,6 @@
schema: ./schema.graphql
overwrite: true
generates:
./fragmentTypes.json:
plugins:
- fragment-matcher
+1 -1
View File
@@ -70,7 +70,7 @@
>{{ event.danceHall.state }}</v-flex
>
</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-icon>mdi-home</v-icon>
<span
+3 -3
View File
@@ -1,6 +1,6 @@
<template>
<div v-if="events && events.events">
<v-layout row wrap v-for="event in events.events" :key="event.id">
<div>
<v-layout row wrap v-for="event in events" :key="event.id">
<v-flex xs12>
<Event
:event="event"
@@ -29,7 +29,7 @@ export default {
required: true
},
events: {
type: Object,
type: Array,
required: true
}
}
+10 -57
View File
@@ -61,7 +61,7 @@
</v-flex>
</v-layout>
<list
:events="data"
:events="events || []"
:has-user="isAuthenticated"
:toggleIgnore="toggleIgnore"
/>
@@ -79,10 +79,10 @@
<script>
import { useRouter, useMutations } from '@u3u/vue-hooks'
import { computed, ref, watch } from '@vue/composition-api'
import useAuth from '../../../plugins/auth'
import { useAuth } from '../../../plugins/auth'
import List from './List'
import { useLazyQuery, useMutation } from '../../../plugins/apollo'
import { useLazyQuery, useMutation, useResult } from '../../../plugins/apollo'
import {
fetchAddress,
findEvents,
@@ -110,6 +110,8 @@ export default {
set: value => router.push(`/?range=${value}`)
})
const [query, { data }] = useLazyQuery(findEvents)
const events = useResult(data, [], data => data.events)
const origins = useResult(data, [], data => data.origins)
watch(
() => range.value,
r => {
@@ -134,14 +136,14 @@ export default {
const origin = ref('')
const fetchEvents = () => {
const origins = [...(data.value.origins || [])]
const originsTemp = [...(origins.value || [])]
if (origin.value) {
origins.push(origin.value)
originsTemp.push(origin.value)
}
query({
variables: {
range: range.value,
origins,
origins: originsTemp,
includeOrigins: isAuthenticated.value || false
}
})
@@ -226,7 +228,8 @@ export default {
authLoading,
isAuthenticated,
range,
data,
events,
origins,
query: fetchEvents,
submitting,
ranges,
@@ -239,53 +242,3 @@ export default {
}
}
</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>
+19 -15
View File
@@ -5,43 +5,38 @@
<v-flex xs12>
<v-card>
<v-container fluid grid-list-md>
<v-layout row wrap v-if="!loading && data">
<v-layout row wrap>
<list
:model="data.bands"
:model="bands || []"
title="filters.band"
type="band"
:toggleIgnore="toggleIgnore"
v-if="data.bands"
/>
<v-flex xs12 sm6 md4 lg3>
<v-layout column>
<list
:model="data.states"
:model="states || []"
title="filters.state"
type="state"
:toggleIgnore="toggleIgnore"
v-if="data.states"
/>
<list
:model="data.municipalities"
:model="municipalities || []"
title="filters.municipality"
type="municipality"
:toggleIgnore="toggleIgnore"
v-if="data.municipalities"
/>
<list
:model="data.cities"
:model="cities || []"
title="filters.city"
type="city"
:toggleIgnore="toggleIgnore"
v-if="data.cities"
/>
<list
:model="data.danceHalls"
:model="danceHalls || []"
title="filters.hall"
type="danceHall"
:toggleIgnore="toggleIgnore"
v-if="data.danceHalls"
/>
</v-layout>
</v-flex>
@@ -74,8 +69,8 @@ import {
} from '~/utils/graph-client'
import List from './List'
import { useMutation, useQuery } from '../../../plugins/apollo'
import useAuth from '../../../plugins/auth'
import { useMutation, useQuery, useResult } from '../../../plugins/apollo'
import { useAuth } from '../../../plugins/auth'
import { useTranslation } from '../../../plugins/i18n'
export default {
@@ -88,6 +83,11 @@ export default {
setTitle(t('app.links.filters'))
const { isAuthenticated } = useAuth()
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 [doToggleIgnoreBand] = useMutation(toggleIgnoreBand)
const [doToggleIgnoreDanceHall] = useMutation(toggleIgnoreDanceHall)
@@ -97,7 +97,7 @@ export default {
const toggleIgnoreSuccess = name => {
return () => {
refetch.value()
refetch()
snackbar.value.color = 'success'
snackbar.value.text = t('filters.success', { name })
snackbar.value.active = true
@@ -146,7 +146,11 @@ export default {
return {
isAuthenticated,
loading,
data,
bands,
danceHalls,
cities,
municipalities,
states,
snackbar,
toggleIgnore
}
+11 -10
View File
@@ -30,8 +30,8 @@
</v-text-field>
</v-flex>
</v-layout>
<template v-if="data && data.origins">
<v-layout row wrap v-for="origin in data.origins" :key="origin">
<template>
<v-layout row wrap v-for="origin in origins" :key="origin">
<v-flex xs12>
<v-tooltip top slot="prepend">
<template v-slot:activator="{ on }">
@@ -65,8 +65,8 @@ import {
removeOrigin,
saveOrigin
} from '../../../utils/graph-client'
import { useLazyQuery, useMutation, useQuery } from '../../../plugins/apollo'
import useAuth from '../../../plugins/auth'
import { useLazyQuery, useMutation, useQuery, useResult } from '../../../plugins/apollo'
import { useAuth } from '../../../plugins/auth'
import { useTranslation } from '../../../plugins/i18n'
export default {
@@ -76,10 +76,11 @@ export default {
setTitle(t('app.links.origins'))
const { isAuthenticated } = useAuth()
const { data, loading, refetch } = useQuery(findOrigins)
const origins = useResult(data, [])
const snackbar = ref({ active: false, color: 'success', text: '' })
const [doSaveOrigin] = useMutation(saveOrigin)
const [doRemoveOrigin] = useMutation(removeOrigin)
const [doFetchAddress, { data: address }] = useLazyQuery(fetchAddress)
const [doFetchAddress] = useLazyQuery(fetchAddress)
const origin = ref('')
const fetchAddressFn = () => {
if (window.navigator) {
@@ -88,23 +89,23 @@ export default {
variables: {
latlng: `${pos.coords.latitude},${pos.coords.longitude}`
}
}).then(() => {
origin.value = address.value.address
}).then(res => {
origin.value = res.address
})
})
}
}
const saveOriginFn = o =>
doSaveOrigin({ variables: { origin: o } }).then(() => {
refetch.value()
refetch()
origin.value = ''
})
const removeOriginFn = o =>
doRemoveOrigin({ variables: { origin: o } }).then(() => refetch.value())
doRemoveOrigin({ variables: { origin: o } }).then(() => refetch())
return {
isAuthenticated,
loading,
data,
origins,
snackbar,
origin,
saveOrigin: saveOriginFn,
+5
View File
@@ -0,0 +1,5 @@
{
"__schema": {
"types": []
}
}
+1 -1
View File
@@ -100,7 +100,7 @@ import dayjs from 'dayjs'
import sv from 'dayjs/locale/sv'
import { setDarkMode } from '../utils/localStorage'
import Themed from './components/themed'
import useAuth from '../plugins/auth'
import { useAuth } from '../plugins/auth'
export default {
components: {
+12
View File
@@ -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
View File
@@ -2,10 +2,26 @@ import translations from './translations'
import numberFormats from './translations/numberFormats'
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: {
graphqlApi: process.env.GRAPHQL_API
},
mode: 'spa',
head: {
link: [
{
@@ -51,12 +67,6 @@ export default {
}
]
},
modules: [
'nuxt-i18n',
'@nuxtjs/sentry',
'@nuxtjs/vuetify',
['@nuxtjs/moment', { locales: ['sv'], defaultLocale: 'sv' }]
],
i18n: {
strategy: 'prefix_and_default',
detectBrowserLanguage: {
@@ -82,6 +92,24 @@ export default {
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: {
dsn: 'https://da2e8d42185a4013909d49955432a116@sentry.io/5187660',
config: {}, // Additional config
@@ -89,27 +117,4 @@ export default {
vuetify: {
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 }
}
]
]
}
}
}
}
+3
View File
@@ -39,6 +39,7 @@
"build": "nuxt build",
"generate": "nuxt generate",
"lint": "eslint --quiet --fix --ext .js,.vue --ignore-path .gitignore .",
"generate-gql": "graphql-codegen",
"precommit": "yarn lint",
"prepush": "yarn test",
"start": "node server/index.js",
@@ -50,6 +51,8 @@
},
"devDependencies": {
"@babel/runtime-corejs3": "^7.8.3",
"@graphql-codegen/cli": "^1.13.1",
"@graphql-codegen/fragment-matcher": "^1.13.1",
"babel-eslint": "^10.0.3",
"cli-engine": "^4.7.6",
"cypress": "^3.1.0",
+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
}
})
}
+54 -43
View File
@@ -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)
}
+1060 -89
View File
File diff suppressed because it is too large Load Diff