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

vueQueryPlugin.ts

101 lines2.6 KB

1import { isVue2 } from 'vue-demi'
2import { isServer } from '@tanstack/query-core'
3import type { QueryClientConfig } from '@tanstack/query-core'
4​
5import { QueryClient } from './queryClient'
6import { getClientKey } from './utils'
7import { setupDevtools } from './devtools/devtools'
8import type { MaybeRefDeep } from './types'
9​
10type ClientPersister = (client: QueryClient) => [() => void, Promise<void>]
11​
12interface CommonOptions {
13 queryClientKey?: string
14 clientPersister?: ClientPersister
16​
17interface ConfigOptions extends CommonOptions {
18 queryClientConfig?: MaybeRefDeep<QueryClientConfig>
20​
21interface ClientOptions extends CommonOptions {
22 queryClient?: QueryClient
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 })
55 }
56​
57 const cleanup = () => {
58 client.unmount()
59 persisterUnmount()
60 }
61​
62 if (app.onUnmount) {
63 app.onUnmount(cleanup)
64 } else {
65 const originalUnmount = app.unmount
66 app.unmount = function vueQueryUnmount() {
67 cleanup()
68 originalUnmount()
69 }
70 }
71​
72 if (isVue2) {
73 app.mixin({
74 beforeCreate() {
75 // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/master/src/apis/inject.ts#L30
76 if (!this._provided) {
77 const provideCache = {}
78 Object.defineProperty(this, '_provided', {
79 get: () => provideCache,
80 set: (v) => Object.assign(provideCache, v),
81 })
82 }
83​
84 this._provided[clientKey] = client
85​
86 if (process.env.NODE_ENV === 'development') {
87 if (this === this.$root) {
88 setupDevtools(this, client)
89 }
90 }
91 },
92 })
93 } else {
94 app.provide(clientKey, client)
95​
96 if (process.env.NODE_ENV === 'development') {
97 setupDevtools(app, client)
98 }
99 }
100 },