Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

vueQueryPlugin.ts

105 lines2.8 KB

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 enableDevtoolsV6Plugin?: boolean
13 queryClientKey?: string
14 clientPersister?: ClientPersister
15 clientPersisterOnSuccess?: (client: QueryClient) => void
17​
18interface ConfigOptions extends CommonOptions {
19 queryClientConfig?: QueryClientConfig
21​
22interface ClientOptions extends CommonOptions {
23 queryClient?: QueryClient
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 client.isRestoring.value = true
51 const [unmount, promise] = options.clientPersister(client)
52 persisterUnmount = unmount
53 promise.then(() => {
54 client.isRestoring.value = false
55 options.clientPersisterOnSuccess?.(client)
56 })
57 }
58​
59 const cleanup = () => {
60 client.unmount()
61 persisterUnmount()
62 }
63​
64 if (app.onUnmount) {
65 app.onUnmount(cleanup)
66 } else {
67 const originalUnmount = app.unmount
68 app.unmount = function vueQueryUnmount() {
69 cleanup()
70 originalUnmount()
71 }
72 }
73​
74 if (isVue2) {
75 app.mixin({
76 beforeCreate() {
77 // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/master/src/apis/inject.ts#L30
78 if (!this._provided) {
79 const provideCache = {}
80 Object.defineProperty(this, '_provided', {
81 get: () => provideCache,
82 set: (v) => Object.assign(provideCache, v),
83 })
84 }
85​
86 this._provided[clientKey] = client
87​
88 if (process.env.NODE_ENV === 'development') {
89 if (this === this.$root && options.enableDevtoolsV6Plugin) {
90 setupDevtools(this, client)
91 }
92 }
93 },
94 })
95 } else {
96 app.provide(clientKey, client)
97​
98 if (process.env.NODE_ENV === 'development') {
99 if (options.enableDevtoolsV6Plugin) {
100 setupDevtools(app, client)
101 }
102 }
103 }
104 },