Open History to see the last commit
1import { isVue2 } from 'vue-demi'
2import { isServer } from '@tanstack/query-core'
3β
4import { QueryClient } from './queryClient'
5import { getClientKey } from './utils'
6import { setupDevtools } from './devtools/devtools'
7import type { QueryClientConfig } from '@tanstack/query-core'
8β
9type ClientPersister = (client: QueryClient) => [() => void, Promise<void>]
10β
11interface CommonOptions {
12 queryClientKey?: string
13 clientPersister?: ClientPersister
14 clientPersisterOnSuccess?: (client: QueryClient) => void
15}
16β
17interface ConfigOptions extends CommonOptions {
18 queryClientConfig?: QueryClientConfig
19}
20β
21interface ClientOptions extends CommonOptions {
22 queryClient?: QueryClient
23}
24β
25export type VueQueryPluginOptions = ConfigOptions | ClientOptions
26β
27export const VueQueryPlugin = {
28 install: (app: any, options: VueQueryPluginOptions = {}) => {
29 const clientKey = getClientKey(options.queryClientKey)
30 let client: QueryClient
31β
32 if ('queryClient' in options && options.queryClient) {
33 client = options.queryClient
34 } else {
35 const clientConfig =
36 'queryClientConfig' in options ? options.queryClientConfig : undefined
37 client = new QueryClient(clientConfig)
38 }
39β
40 if (!isServer) {
41 client.mount()
42 }
43β
44 let persisterUnmount = () => {
45 // noop
46 }
47β
48 if (options.clientPersister) {
49 client.isRestoring.value = true
50 const [unmount, promise] = options.clientPersister(client)
51 persisterUnmount = unmount
52 promise.then(() => {
53 client.isRestoring.value = false
54 options.clientPersisterOnSuccess?.(client)
55 })
56 }
57β
58 const cleanup = () => {
59 client.unmount()
60 persisterUnmount()
61 }
62β
63 if (app.onUnmount) {
64 app.onUnmount(cleanup)
65 } else {
66 const originalUnmount = app.unmount
67 app.unmount = function vueQueryUnmount() {
68 cleanup()
69 originalUnmount()
70 }
71 }
72β
73 if (isVue2) {
74 app.mixin({
75 beforeCreate() {
76 // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/master/src/apis/inject.ts#L30
77 if (!this._provided) {
78 const provideCache = {}
79 Object.defineProperty(this, '_provided', {
80 get: () => provideCache,
81 set: (v) => Object.assign(provideCache, v),
82 })
83 }
84β
85 this._provided[clientKey] = client
86β
87 if (process.env.NODE_ENV === 'development') {
88 if (this === this.$root) {
89 setupDevtools(this, client)
90 }
91 }
92 },
93 })
94 } else {
95 app.provide(clientKey, client)
96β
97 if (process.env.NODE_ENV === 'development') {
98 setupDevtools(app, client)
99 }
100 }
101 },
102}