Skip to content

Commit

Permalink
fix: ensure useCookie called with context
Browse files Browse the repository at this point in the history
Closes #524
  • Loading branch information
Diizzayy committed Mar 1, 2024
1 parent 3ba2baa commit 3cb6444
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 22 deletions.
30 changes: 17 additions & 13 deletions playground/components/GithubDemo.vue
Original file line number Diff line number Diff line change
Expand Up @@ -47,29 +47,34 @@
<script lang="ts" setup>
import type { ViewerT, DiscussionT } from '~/types'
import discussions from '~/queries/discussions.gql'
import { NuxtApollo } from '#apollo'
const { getToken, onLogin, onLogout } = useApollo()
const githubToken = ref<string | null>(null)
const githubToken = useState<string | null | undefined>()
// for testing with cookie `tokenStorage`
if (process.server) { githubToken.value = await getToken('github') }
onMounted(async () => {
if (import.meta.server && NuxtApollo.clients?.github?.tokenStorage === 'cookie') {
githubToken.value = await getToken('github')
})
} else if (import.meta.client) {
onMounted(async () => {
githubToken.value = await getToken('github')
})
}
const queryViewer = gql`query viwer { viewer { login } }`
const output = ref()
if (githubToken.value) {
const whoAmI = await useAsyncQuery({ query: queryViewer, clientId: 'github' })
const whoAmI = await useAsyncQuery({ query: queryViewer, clientId: 'github' }, {
immediate: !!githubToken.value
})
if (whoAmI?.data.value) {
output.value = whoAmI.data.value
}
}
watch(whoAmI.data, (data) => {
if (!data) { return }
output.value = data
}, { immediate: true })
const getViewer = () => {
const { onResult, onError } = useQuery<ViewerT>(queryViewer, null, { clientId: 'github', fetchPolicy: 'cache-and-network' })
Expand All @@ -90,6 +95,5 @@ const setToken = () => {
onLogin(githubToken.value, 'github')
}
const clearToken = () => onLogout('github').then(() => (githubToken.value = null))
const clearToken = () => onLogout('github', true).then(() => (githubToken.value = null))
</script>
7 changes: 6 additions & 1 deletion playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@ export default defineNuxtConfig({
default: './apollo/default.ts',
github: {
httpEndpoint: 'https://api.github.com/graphql',
tokenStorage: 'localStorage'
tokenStorage: 'cookie'
},
todos: {
httpEndpoint: 'https://nuxt-gql-server-2gl6xp7kua-ue.a.run.app/query',
wsEndpoint: 'wss://nuxt-gql-server-2gl6xp7kua-ue.a.run.app/query',
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network'
}
},
httpLinkOptions: {
headers: {
'X-CUSTOM-HEADER': '123'
Expand Down
2 changes: 1 addition & 1 deletion playground/queries/discussions.gql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
query discussions {
repository(owner: "nuxt", name: "framework") {
repository(owner: "nuxt", name: "nuxt") {
discussions(first: 5) {
nodes {
author {
Expand Down
20 changes: 13 additions & 7 deletions src/runtime/composables.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { hash } from 'ohash'
import { print } from 'graphql'
import type { ApolloClient, OperationVariables, QueryOptions, DefaultContext } from '@apollo/client'
import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app'
import type { AsyncData, AsyncDataOptions, NuxtError, NuxtApp } from 'nuxt/app'
import type { RestartableClient } from './ws'
import { ref, isRef, reactive, useCookie, useNuxtApp, useAsyncData } from '#imports'
import { NuxtApollo } from '#apollo'
Expand Down Expand Up @@ -192,45 +192,51 @@ export function useApollo (): {
*
* @param {string} token The token to be applied.
* @param {string} client - Name of the Apollo client. Defaults to `default`.
* @param {boolean} skipResetStore - If `true`, the cache will not be reset.
* @param {boolean} skipResetStore - If `false`, Resets your entire store by clearing out your cache and then re-executing all of your active queries.
* */
onLogin: (token?: string, client?: ApolloClientKeys, skipResetStore?: boolean) => Promise<void>

/**
* Remove the auth token from the Apollo client, and optionally reset it's cache.
*
* @param {string} client - Name of the Apollo client. Defaults to `default`.
* @param {boolean} skipResetStore - If `true`, the cache will not be reset.
* @param {boolean} skipResetStore - If `false`, Resets your entire store by clearing out your cache and then re-executing all of your active queries.
* */
onLogout: (client?: ApolloClientKeys, skipResetStore?: boolean) => Promise<void>
}

export function useApollo () {
const nuxtApp = useNuxtApp() as {
_apolloClients?: Record<ApolloClientKeys, ApolloClient<any>>;
_apolloWsClients?: Record<ApolloClientKeys, RestartableClient>;
const nuxtApp = useNuxtApp() as NuxtApp & {
_apolloClients?: Record<ApolloClientKeys, ApolloClient<any>>
_apolloWsClients?: Record<ApolloClientKeys, RestartableClient>
}

const getToken = async (client?: ApolloClientKeys) => {
client = client || 'default'

const conf = NuxtApollo?.clients?.[client]

if (!conf) { return }

const token = ref<string | null>(null)
await (nuxtApp as ReturnType<typeof useNuxtApp>).callHook('apollo:auth', { token, client })

if (token.value) { return token.value }

const tokenName = conf.tokenName!

return conf?.tokenStorage === 'cookie' ? useCookie(tokenName).value : (process.client && localStorage.getItem(tokenName)) || null
return conf?.tokenStorage === 'cookie'
? nuxtApp.runWithContext(() => useCookie(tokenName).value)
: (process.client && localStorage.getItem(tokenName)) || null
}
type TAuthUpdate = {token?: string, client?: ApolloClientKeys, mode: 'login' | 'logout', skipResetStore?: boolean}
const updateAuth = async ({ token, client, mode, skipResetStore }: TAuthUpdate) => {
client = client || 'default'

const conf = NuxtApollo?.clients?.[client]

if (!conf) { return }

const tokenName = client && conf.tokenName!

if (conf?.tokenStorage === 'cookie') {
Expand Down

0 comments on commit 3cb6444

Please sign in to comment.