Open History to see the last commit
1import { isVue2 } from 'vue-demi'
2β
3import { QueryClient } from './queryClient'
4import { getClientKey } from './utils'
5import { setupDevtools } from './devtools/devtools'
6import type { QueryClientConfig } from './types'
7β
8type ClientPersister = (client: QueryClient) => [() => void, Promise<void>]
9β
10interface CommonOptions {
11 enableDevtoolsV6Plugin?: boolean
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 (!client.isServer) {
41 client.mount()
42 }
43β
44 let persisterUnmount = () => {
45 // noop
46 }
47β
48 if (options.clientPersister) {
49 if (client.isRestoring) {
50 client.isRestoring.value = true
51 }
52 const [unmount, promise] = options.clientPersister(client)
53 persisterUnmount = unmount
54 promise.then(() => {
55 if (client.isRestoring) {
56 client.isRestoring.value = false
57 }
58 options.clientPersisterOnSuccess?.(client)
59 })
60 }
61β
62 const cleanup = () => {
63 client.unmount()
64 persisterUnmount()
65 }
66β
67 if (app.onUnmount) {
68 app.onUnmount(cleanup)
69 } else {
70 const originalUnmount = app.unmount
71 app.unmount = function vueQueryUnmount() {
72 cleanup()
73 originalUnmount()
74 }
75 }
76β
77 if (isVue2) {
78 app.mixin({
79 beforeCreate() {
80 // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/master/src/apis/inject.ts#L30
81 if (!this._provided) {
82 const provideCache = {}
83 Object.defineProperty(this, '_provided', {
84 get: () => provideCache,
85 set: (v) => Object.assign(provideCache, v),
86 })
87 }
88β
89 this._provided[clientKey] = client
90β
91 if (process.env.NODE_ENV === 'development') {
92 if (this === this.$root && options.enableDevtoolsV6Plugin) {
93 setupDevtools(this, client)
94 }
95 }
96 },
97 })
98 } else {
99 app.provide(clientKey, client)
100β
101 if (process.env.NODE_ENV === 'development') {
102 if (options.enableDevtoolsV6Plugin) {
103 setupDevtools(app, client)
104 }
105 }
106 }
107 },
108}