Skip to content

Commit 3cb6444

Browse files
committed
fix: ensure useCookie called with context
Closes #524
1 parent 3ba2baa commit 3cb6444

File tree

4 files changed

+37
-22
lines changed

4 files changed

+37
-22
lines changed

playground/components/GithubDemo.vue

+17-13
Original file line numberDiff line numberDiff line change
@@ -47,29 +47,34 @@
4747
<script lang="ts" setup>
4848
import type { ViewerT, DiscussionT } from '~/types'
4949
import discussions from '~/queries/discussions.gql'
50+
import { NuxtApollo } from '#apollo'
5051
5152
const { getToken, onLogin, onLogout } = useApollo()
5253
53-
const githubToken = ref<string | null>(null)
54+
const githubToken = useState<string | null | undefined>()
5455
5556
// for testing with cookie `tokenStorage`
56-
if (process.server) { githubToken.value = await getToken('github') }
57-
58-
onMounted(async () => {
57+
if (import.meta.server && NuxtApollo.clients?.github?.tokenStorage === 'cookie') {
5958
githubToken.value = await getToken('github')
60-
})
59+
} else if (import.meta.client) {
60+
onMounted(async () => {
61+
githubToken.value = await getToken('github')
62+
})
63+
}
6164
6265
const queryViewer = gql`query viwer { viewer { login } }`
6366
6467
const output = ref()
6568
66-
if (githubToken.value) {
67-
const whoAmI = await useAsyncQuery({ query: queryViewer, clientId: 'github' })
69+
const whoAmI = await useAsyncQuery({ query: queryViewer, clientId: 'github' }, {
70+
immediate: !!githubToken.value
71+
})
6872
69-
if (whoAmI?.data.value) {
70-
output.value = whoAmI.data.value
71-
}
72-
}
73+
watch(whoAmI.data, (data) => {
74+
if (!data) { return }
75+
76+
output.value = data
77+
}, { immediate: true })
7378
7479
const getViewer = () => {
7580
const { onResult, onError } = useQuery<ViewerT>(queryViewer, null, { clientId: 'github', fetchPolicy: 'cache-and-network' })
@@ -90,6 +95,5 @@ const setToken = () => {
9095
9196
onLogin(githubToken.value, 'github')
9297
}
93-
const clearToken = () => onLogout('github').then(() => (githubToken.value = null))
94-
98+
const clearToken = () => onLogout('github', true).then(() => (githubToken.value = null))
9599
</script>

playground/nuxt.config.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,16 @@ export default defineNuxtConfig({
1313
default: './apollo/default.ts',
1414
github: {
1515
httpEndpoint: 'https://api.github.com/graphql',
16-
tokenStorage: 'localStorage'
16+
tokenStorage: 'cookie'
1717
},
1818
todos: {
1919
httpEndpoint: 'https://nuxt-gql-server-2gl6xp7kua-ue.a.run.app/query',
2020
wsEndpoint: 'wss://nuxt-gql-server-2gl6xp7kua-ue.a.run.app/query',
21+
defaultOptions: {
22+
watchQuery: {
23+
fetchPolicy: 'cache-and-network'
24+
}
25+
},
2126
httpLinkOptions: {
2227
headers: {
2328
'X-CUSTOM-HEADER': '123'

playground/queries/discussions.gql

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
query discussions {
2-
repository(owner: "nuxt", name: "framework") {
2+
repository(owner: "nuxt", name: "nuxt") {
33
discussions(first: 5) {
44
nodes {
55
author {

src/runtime/composables.ts

+13-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { hash } from 'ohash'
22
import { print } from 'graphql'
33
import type { ApolloClient, OperationVariables, QueryOptions, DefaultContext } from '@apollo/client'
4-
import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app'
4+
import type { AsyncData, AsyncDataOptions, NuxtError, NuxtApp } from 'nuxt/app'
55
import type { RestartableClient } from './ws'
66
import { ref, isRef, reactive, useCookie, useNuxtApp, useAsyncData } from '#imports'
77
import { NuxtApollo } from '#apollo'
@@ -192,45 +192,51 @@ export function useApollo (): {
192192
*
193193
* @param {string} token The token to be applied.
194194
* @param {string} client - Name of the Apollo client. Defaults to `default`.
195-
* @param {boolean} skipResetStore - If `true`, the cache will not be reset.
195+
* @param {boolean} skipResetStore - If `false`, Resets your entire store by clearing out your cache and then re-executing all of your active queries.
196196
* */
197197
onLogin: (token?: string, client?: ApolloClientKeys, skipResetStore?: boolean) => Promise<void>
198198

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

208208
export function useApollo () {
209-
const nuxtApp = useNuxtApp() as {
210-
_apolloClients?: Record<ApolloClientKeys, ApolloClient<any>>;
211-
_apolloWsClients?: Record<ApolloClientKeys, RestartableClient>;
209+
const nuxtApp = useNuxtApp() as NuxtApp & {
210+
_apolloClients?: Record<ApolloClientKeys, ApolloClient<any>>
211+
_apolloWsClients?: Record<ApolloClientKeys, RestartableClient>
212212
}
213213

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

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

219+
if (!conf) { return }
220+
219221
const token = ref<string | null>(null)
220222
await (nuxtApp as ReturnType<typeof useNuxtApp>).callHook('apollo:auth', { token, client })
221223

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

224226
const tokenName = conf.tokenName!
225227

226-
return conf?.tokenStorage === 'cookie' ? useCookie(tokenName).value : (process.client && localStorage.getItem(tokenName)) || null
228+
return conf?.tokenStorage === 'cookie'
229+
? nuxtApp.runWithContext(() => useCookie(tokenName).value)
230+
: (process.client && localStorage.getItem(tokenName)) || null
227231
}
228232
type TAuthUpdate = {token?: string, client?: ApolloClientKeys, mode: 'login' | 'logout', skipResetStore?: boolean}
229233
const updateAuth = async ({ token, client, mode, skipResetStore }: TAuthUpdate) => {
230234
client = client || 'default'
231235

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

238+
if (!conf) { return }
239+
234240
const tokenName = client && conf.tokenName!
235241

236242
if (conf?.tokenStorage === 'cookie') {

0 commit comments

Comments
 (0)