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