@hz52410/uni-query 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +247 -0
- package/dist/index.cjs.js +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.esm.js +1203 -0
- package/dist/infiniteQueryOptions.d.ts +15 -0
- package/dist/mutationCache.d.ts +8 -0
- package/dist/query-core/index.d.ts +12 -0
- package/dist/query-core/infiniteQueryObserver.d.ts +31 -0
- package/dist/query-core/mutationCache.d.ts +43 -0
- package/dist/query-core/mutationObserver.d.ts +43 -0
- package/dist/query-core/queriesObserver.d.ts +27 -0
- package/dist/query-core/queryCache.d.ts +40 -0
- package/dist/query-core/queryClient.d.ts +133 -0
- package/dist/query-core/queryObserver.d.ts +67 -0
- package/dist/query-core/types.d.ts +236 -0
- package/dist/query-core/utils.d.ts +10 -0
- package/dist/queryCache.d.ts +8 -0
- package/dist/queryClient.d.ts +37 -0
- package/dist/queryOptions.d.ts +9 -0
- package/dist/types.d.ts +33 -0
- package/dist/useBaseQuery.d.ts +15 -0
- package/dist/useInfiniteQuery.d.ts +13 -0
- package/dist/useIsFetching.d.ts +7 -0
- package/dist/useMutation.d.ts +16 -0
- package/dist/useMutationState.d.ts +12 -0
- package/dist/useQueries.d.ts +84 -0
- package/dist/useQuery.d.ts +19 -0
- package/dist/useQueryClient.d.ts +3 -0
- package/dist/utils.d.ts +7 -0
- package/dist/vueQueryPlugin.d.ts +20 -0
- package/package.json +56 -0
package/README.md
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
# UniQuery
|
|
2
|
+
|
|
3
|
+
一个专为 uni-app 生态设计的轻量级数据获取库,提供类似 React Query 的请求管理、缓存和自动刷新功能。
|
|
4
|
+
|
|
5
|
+
## 特性
|
|
6
|
+
|
|
7
|
+
- 🚀 **跨平台兼容**:一套 API 支持小程序、App 和 H5
|
|
8
|
+
- 💾 **智能缓存**:LRU 算法管理缓存,自动过期清理
|
|
9
|
+
- 🔄 **自动重试**:请求失败自动重试机制
|
|
10
|
+
- 📦 **请求去重**:相同请求自动合并,避免重复请求
|
|
11
|
+
- 🌊 **流式支持**:支持微信小程序流式数据传输
|
|
12
|
+
- 🎯 **TypeScript**:完整的 TypeScript 类型支持
|
|
13
|
+
- ⚡ **轻量高效**:针对小程序环境优化
|
|
14
|
+
|
|
15
|
+
## 安装
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install z-query
|
|
19
|
+
# 或
|
|
20
|
+
yarn add z-query
|
|
21
|
+
# 或
|
|
22
|
+
pnpm add z-query
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## 快速开始
|
|
26
|
+
|
|
27
|
+
### 全局配置
|
|
28
|
+
|
|
29
|
+
在项目的 `main.js` 中进行全局配置:
|
|
30
|
+
|
|
31
|
+
```javascript
|
|
32
|
+
import { createApp } from 'vue'
|
|
33
|
+
import { UniQueryPlugin } from 'z-query'
|
|
34
|
+
|
|
35
|
+
const app = createApp(App)
|
|
36
|
+
|
|
37
|
+
// 注册 UniQuery 插件
|
|
38
|
+
app.use(UniQueryPlugin, {
|
|
39
|
+
staleTime: 5 * 60 * 1000, // 默认缓存5分钟
|
|
40
|
+
cacheTime: 24 * 60 * 60 * 1000, // 默认保留24小时
|
|
41
|
+
manual: false, // 自动执行查询
|
|
42
|
+
retry: 3, // 自动重试次数
|
|
43
|
+
retryDelay: 1000, // 重试延迟时间
|
|
44
|
+
cacheCapacity: 100, // 缓存容量限制
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
app.mount('#app')
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### 基本使用
|
|
51
|
+
|
|
52
|
+
```vue
|
|
53
|
+
<template>
|
|
54
|
+
<view v-if="loading">加载中...</view>
|
|
55
|
+
<view v-else-if="error">错误: {{ error?.message }}</view>
|
|
56
|
+
<view v-else>{{ data?.title }}</view>
|
|
57
|
+
<button @click="refetch">刷新</button>
|
|
58
|
+
</template>
|
|
59
|
+
|
|
60
|
+
<script setup>
|
|
61
|
+
import { useQuery, fetchData } from 'z-query'
|
|
62
|
+
|
|
63
|
+
const { data, loading, error, refetch } = useQuery({
|
|
64
|
+
queryKey: ['post', 1],
|
|
65
|
+
queryFn: () => fetchData('/api/posts/1'),
|
|
66
|
+
staleTime: 30 * 1000, // 缓存30秒
|
|
67
|
+
retry: 2, // 失败后重试2次
|
|
68
|
+
})
|
|
69
|
+
</script>
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## API 参考
|
|
73
|
+
|
|
74
|
+
### useQuery
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
interface UseQueryOptions<T> {
|
|
78
|
+
queryKey: string[] // 唯一标识查询的键
|
|
79
|
+
queryFn: () => Promise<T> // 执行查询的函数
|
|
80
|
+
staleTime?: number // 缓存过期时间(毫秒)
|
|
81
|
+
cacheTime?: number // 缓存保留时间(毫秒)
|
|
82
|
+
manual?: boolean // 是否手动触发查询
|
|
83
|
+
retry?: number // 自动重试次数
|
|
84
|
+
retryDelay?: number // 重试延迟时间(毫秒)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function useQuery<T>(options: UseQueryOptions<T>): {
|
|
88
|
+
data: Ref<T | null> // 在模板中自动解包,在 script 中使用 .value
|
|
89
|
+
loading: Ref<boolean>
|
|
90
|
+
isLoading: Ref<boolean>
|
|
91
|
+
error: Ref<Error | null>
|
|
92
|
+
refetch: () => Promise<T>
|
|
93
|
+
status: Ref<'loading' | 'success' | 'error' | 'idle'>
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### fetchData
|
|
98
|
+
|
|
99
|
+
通用的请求函数,自动适配小程序和 H5 环境:
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
import { fetchData } from 'z-query'
|
|
103
|
+
|
|
104
|
+
// 基本用法
|
|
105
|
+
const data = await fetchData('/api/posts', {
|
|
106
|
+
method: 'GET',
|
|
107
|
+
headers: {
|
|
108
|
+
'Authorization': 'Bearer token'
|
|
109
|
+
}
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
// POST 请求
|
|
113
|
+
const result = await fetchData('/api/posts', {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
body: { title: 'New Post' }
|
|
116
|
+
})
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## 小程序特有功能
|
|
120
|
+
|
|
121
|
+
### 流式请求支持
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
const { data, loading } = useQuery({
|
|
125
|
+
queryKey: ['ai-response'],
|
|
126
|
+
queryFn: () => fetchData('/api/ai-response', {
|
|
127
|
+
method: 'POST',
|
|
128
|
+
body: { question: '你好' },
|
|
129
|
+
enableChunked: true, // 启用流式传输
|
|
130
|
+
chunkDecoder: (data) => {
|
|
131
|
+
// #ifdef MP-WEIXIN
|
|
132
|
+
return new TextDecoder().decode(data as Uint8Array)
|
|
133
|
+
// #endif
|
|
134
|
+
},
|
|
135
|
+
}),
|
|
136
|
+
staleTime: 0,
|
|
137
|
+
manual: true,
|
|
138
|
+
})
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## 缓存管理
|
|
142
|
+
|
|
143
|
+
UniQuery 使用 LRU(最近最少使用)算法管理缓存,并自动处理过期清理:
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
import { QueryCacheManager } from 'z-query'
|
|
147
|
+
|
|
148
|
+
// 手动管理缓存
|
|
149
|
+
const cacheManager = new QueryCacheManager(100) // 容量100
|
|
150
|
+
|
|
151
|
+
// 获取缓存
|
|
152
|
+
const cached = cacheManager.get('key')
|
|
153
|
+
|
|
154
|
+
// 设置缓存
|
|
155
|
+
cacheManager.set('key', data, staleTime, cacheTime)
|
|
156
|
+
|
|
157
|
+
// 删除缓存
|
|
158
|
+
cacheManager.delete('key')
|
|
159
|
+
|
|
160
|
+
// 清空所有缓存
|
|
161
|
+
cacheManager.clear()
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## 最佳实践
|
|
165
|
+
|
|
166
|
+
### 1. 合理配置缓存时间
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
// 静态数据(如配置信息)
|
|
170
|
+
useQuery({
|
|
171
|
+
queryKey: ['config'],
|
|
172
|
+
queryFn: () => fetchData('/api/config'),
|
|
173
|
+
staleTime: 24 * 60 * 60 * 1000, // 缓存24小时
|
|
174
|
+
cacheTime: 30 * 24 * 60 * 60 * 1000, // 保留30天
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
// 动态数据(如用户信息)
|
|
178
|
+
useQuery({
|
|
179
|
+
queryKey: ['user-info'],
|
|
180
|
+
queryFn: () => fetchData('/api/user-info'),
|
|
181
|
+
staleTime: 5 * 60 * 1000, // 缓存5分钟
|
|
182
|
+
cacheTime: 24 * 60 * 60 * 1000, // 保留24小时
|
|
183
|
+
})
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### 2. 手动触发查询
|
|
187
|
+
|
|
188
|
+
```typescript
|
|
189
|
+
const { data, loading, refetch } = useQuery({
|
|
190
|
+
queryKey: ['todos'],
|
|
191
|
+
queryFn: () => fetchData('/api/todos'),
|
|
192
|
+
manual: true, // 手动触发
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
// 在需要时触发
|
|
196
|
+
onMounted(() => {
|
|
197
|
+
refetch()
|
|
198
|
+
})
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### 3. 错误处理
|
|
202
|
+
|
|
203
|
+
```vue
|
|
204
|
+
<script setup>
|
|
205
|
+
import { useQuery, fetchData } from 'z-query'
|
|
206
|
+
import { watch } from 'vue'
|
|
207
|
+
|
|
208
|
+
const { data, loading, error } = useQuery({
|
|
209
|
+
queryKey: ['posts'],
|
|
210
|
+
queryFn: () => fetchData('/api/posts'),
|
|
211
|
+
retry: 3, // 自动重试3次
|
|
212
|
+
retryDelay: 1000, // 每次重试间隔1秒
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
watch(error, (err) => {
|
|
216
|
+
if (err) {
|
|
217
|
+
console.error('请求失败:', err)
|
|
218
|
+
// 处理错误
|
|
219
|
+
}
|
|
220
|
+
})
|
|
221
|
+
</script>
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## 开发
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
# 安装依赖
|
|
228
|
+
npm install
|
|
229
|
+
|
|
230
|
+
# 开发模式(监听文件变化)
|
|
231
|
+
npm run dev
|
|
232
|
+
|
|
233
|
+
# 构建
|
|
234
|
+
npm run build
|
|
235
|
+
|
|
236
|
+
# 类型检查
|
|
237
|
+
npm run type-check
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## 许可证
|
|
241
|
+
|
|
242
|
+
MIT
|
|
243
|
+
|
|
244
|
+
## 贡献
|
|
245
|
+
|
|
246
|
+
欢迎提交 Issue 和 Pull Request!
|
|
247
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("vue");let D=class{constructor(){this.queries=new Map}add(e){this.queries.set(e.queryHash,e)}remove(e){this.queries.delete(e.queryHash)}find(e){const t=this.hashQueryKey(e.queryKey);return this.queries.get(t)}findAll(e={}){const t=[];for(const s of this.queries.values())this.matchQuery(s,e)&&t.push(s);return t}clear(){this.queries.clear()}subscribe(e){return()=>{}}hashQueryKey(e){return JSON.stringify(e)}matchQuery(e,t){if(t.queryKey){const s=this.hashQueryKey(t.queryKey);return t.exact?e.queryHash===s:e.queryHash.startsWith(s)}return t.predicate?t.predicate(e):!0}},P=class{constructor(){this.mutations=new Map,this.mutationId=0}add(e){this.mutations.set(e.mutationId,e)}remove(e){this.mutations.delete(e.mutationId)}find(e){for(const t of this.mutations.values())if(this.matchMutation(t,e))return t}findAll(e={}){const t=[];for(const s of this.mutations.values())this.matchMutation(s,e)&&t.push(s);return t}clear(){this.mutations.clear()}subscribe(e){return()=>{}}generateMutationId(){return++this.mutationId}matchMutation(e,t){return!(t.mutationKey&&e.options.mutationKey&&!this.matchKeys(e.options.mutationKey,t.mutationKey,t.exact)||t.status&&e.state.status!==t.status||t.predicate&&!t.predicate(e))}matchKeys(e,t,s){return s?JSON.stringify(e)===JSON.stringify(t):JSON.stringify(e).startsWith(JSON.stringify(t))}},V=class{constructor(e={}){this.queryCache=e.queryCache||new D,this.mutationCache=e.mutationCache||new P,this.defaultOptions=e.defaultOptions||{}}mount(){}unmount(){this.queryCache.clear(),this.mutationCache.clear()}getQueryData(e){const t=this.queryCache.find({queryKey:e,exact:!0});return t==null?void 0:t.state.data}setQueryData(e,t,s){const r=this.queryCache.find({queryKey:e,exact:!0});if(!r)return;const i=r.state.data,o=typeof t=="function"?t(i):t;return r.state={...r.state,data:o,dataUpdatedAt:(s==null?void 0:s.updatedAt)||Date.now()},o}setQueriesData(e,t,s){return this.queryCache.findAll(e).map(i=>{const o=this.setQueryData(i.queryKey,t,s);return[i.queryKey,o]})}getQueryState(e){const t=this.queryCache.find({queryKey:e,exact:!0});return t==null?void 0:t.state}getQueriesData(e){return this.queryCache.findAll(e).map(s=>[s.queryKey,s.state.data])}getQuery(e){return this.queryCache.find({queryKey:e,exact:!0})}getQueries(e={}){return this.queryCache.findAll(e)}getMutations(e={}){return this.mutationCache.findAll(e)}isFetching(e={}){return this.queryCache.findAll(e).filter(s=>s.state.fetchStatus==="fetching").length}isMutating(e={}){return this.mutationCache.findAll(e).filter(s=>s.state.status==="loading").length}defaultQueryOptions(e){return{...this.defaultOptions.queries||{},...e,_defaulted:!0}}defaultMutationOptions(e){return{...this.defaultOptions.mutations||{},...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setQueryDefaults(e,t){}getQueryDefaults(e){return{}}setMutationDefaults(e,t){}getMutationDefaults(e){return{}}async ensureQueryData(e){const t=this.getQuery(e.queryKey);return t&&t.state.data!==void 0?t.state.data:this.fetchQuery(e)}async fetchQuery(e){const t=this.defaultQueryOptions(e),s=await t.queryFn({queryKey:t.queryKey});return t.select?t.select(s):s}async prefetchQuery(e){await this.fetchQuery(e)}async fetchInfiniteQuery(e){return{pages:[await e.queryFn({queryKey:e.queryKey})],pageParams:[e.initialPageParam]}}async prefetchInfiniteQuery(e){await this.fetchInfiniteQuery(e)}removeQueries(e={}){this.queryCache.findAll(e).forEach(s=>this.queryCache.remove(s))}async resetQueries(e={},t){this.queryCache.findAll(e).forEach(r=>{r.state={...r.state,data:void 0,error:null,status:"pending",fetchStatus:"idle"}})}async cancelQueries(e={},t){}async invalidateQueries(e={},t){this.queryCache.findAll(e).forEach(r=>{r.state.isInvalidated=!0})}async refetchQueries(e={},t){const s=this.queryCache.findAll(e);for(const r of s)if(r.options.queryFn)try{const i=await r.options.queryFn({queryKey:r.queryKey});r.state={...r.state,data:i,status:"success",fetchStatus:"idle",dataUpdatedAt:Date.now()}}catch(i){r.state={...r.state,error:i,status:"error",fetchStatus:"idle",errorUpdatedAt:Date.now()}}}};function E(u){return JSON.stringify(u)}function q(u,e){return typeof u=="function"?u(...e):u===!0}class b{constructor(e,t){this.subscribers=new Set,this.client=e,this.options=t,this.query=this.client.getQuery(t.queryKey),this.query||this.createQuery(),this.currentResult=this.createResult(),t.enabled!==!1&&this.shouldFetch()&&this.fetch().catch(()=>{})}createQuery(){const e=E(this.options.queryKey),t={queryKey:this.options.queryKey,queryHash:e,state:this.createInitialState(),options:this.options};this.client.queryCache.add(t),this.query=t}shouldFetch(){if(!this.query)return!0;const e=this.query.state;if(e.data===void 0)return!0;if(this.options.staleTime!==void 0&&this.options.staleTime>0){const t=Date.now(),s=this.options.staleTime;if(t-e.dataUpdatedAt>s)return!0}return!1}subscribe(e){return this.subscribers.add(e),e(this.currentResult),()=>{this.subscribers.delete(e)}}getCurrentResult(){return this.currentResult}getOptimisticResult(e){return this.createResult()}getCurrentQuery(){return this.query}setOptions(e){this.options=e,this.query=this.client.getQuery(e.queryKey),this.query||this.createQuery(),this.updateResult(),e.enabled!==!1&&this.shouldFetch()&&this.fetch().catch(()=>{})}fetchOptimistic(e){return this.fetch()}async fetch(){if(!this.options.queryFn)throw new Error("queryFn is required");this.query||this.createQuery(),this.query&&(this.query.state={...this.query.state,fetchStatus:"fetching"},this.updateResult());try{const e=await this.options.queryFn({queryKey:this.options.queryKey}),t=this.options.select?this.options.select(e):e;return this.query&&(this.query.state={...this.query.state,data:t,status:"success",fetchStatus:"idle",dataUpdatedAt:Date.now(),error:null,errorUpdateCount:0,failureCount:0}),this.updateResult(),this.currentResult}catch(e){if(this.query){const t=(this.query.state.errorUpdateCount||0)+1;this.query.state={...this.query.state,error:e,status:"error",fetchStatus:"idle",errorUpdatedAt:Date.now(),errorUpdateCount:t,failureCount:t,failureReason:e}}throw this.updateResult(),e}}createResult(){var r;const t=((r=this.query)==null?void 0:r.state)||this.createInitialState();return{data:this.options.select&&t.data?this.options.select(t.data):t.data,dataUpdatedAt:t.dataUpdatedAt,error:t.error,errorUpdatedAt:t.errorUpdatedAt,errorUpdateCount:t.errorUpdateCount,failureCount:t.failureCount,failureReason:t.failureReason,fetchFailureCount:t.fetchFailureCount,fetchFailureReason:t.fetchFailureReason,fetchStatus:t.fetchStatus,isError:t.status==="error",isFetched:t.dataUpdatedAt>0,isFetchedAfterMount:t.dataUpdatedAt>0&&t.fetchStatus!=="fetching",isFetching:t.fetchStatus==="fetching",isInitialLoading:t.status==="pending"&&t.fetchStatus==="fetching",isLoading:t.status==="pending",isLoadingError:t.status==="error"&&t.fetchStatus!=="fetching",isPaused:t.fetchStatus==="paused",isPlaceholderData:!1,isRefetchError:t.status==="error"&&t.fetchStatus==="fetching",isRefetching:t.status==="success"&&t.fetchStatus==="fetching",isStale:this.isStale(t),isSuccess:t.status==="success",refetch:this.refetch.bind(this),status:t.status}}createInitialState(){return{data:void 0,dataUpdatedAt:0,error:null,errorUpdatedAt:0,errorUpdateCount:0,failureCount:0,failureReason:null,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:void 0,isInvalidated:!1,status:"pending",fetchStatus:"idle"}}isStale(e){return this.options.staleTime?Date.now()-e.dataUpdatedAt>this.options.staleTime:!0}updateResult(){this.currentResult=this.createResult(),this.subscribers.forEach(e=>e(this.currentResult))}async refetch(e){return this.fetch()}}class A{constructor(e,t){this.subscribers=new Set,this.client=e,this.options=t,this.mutation=this.createMutation(),this.currentResult=this.createResult()}subscribe(e){return this.subscribers.add(e),e(this.currentResult),()=>{this.subscribers.delete(e)}}getCurrentResult(){return this.currentResult}setOptions(e){this.options=e,this.mutation.options=e,this.updateResult()}async mutate(e,t){this.mutation.state={...this.mutation.state,status:"loading",isLoading:!0,variables:e},this.updateResult();let s;try{this.options.onMutate&&(s=await this.options.onMutate(e),this.mutation.state.context=s);const r=await this.options.mutationFn(e);return this.mutation.state={...this.mutation.state,data:r,status:"success",isLoading:!1,isSuccess:!0,isError:!1},this.updateResult(),this.options.onSuccess&&await this.options.onSuccess(r,e,s),r}catch(r){throw this.mutation.state={...this.mutation.state,error:r,status:"error",isLoading:!1,isSuccess:!1,isError:!0,failureCount:(this.mutation.state.failureCount||0)+1,failureReason:r},this.updateResult(),this.options.onError&&await this.options.onError(r,e,s),r}finally{this.options.onSettled&&await this.options.onSettled(this.mutation.state.data,this.mutation.state.error,e,s)}}createMutation(){return{mutationId:this.client.mutationCache.generateMutationId(),options:this.options,state:this.createInitialResult()}}createInitialResult(){return{data:void 0,error:null,failureCount:0,failureReason:null,isError:!1,isIdle:!0,isPaused:!1,isLoading:!1,isSuccess:!1,mutate:()=>{},mutateAsync:async()=>{throw new Error("Not implemented")},reset:()=>{},status:"idle",variables:void 0,context:void 0}}createResult(){return{...this.mutation.state,mutate:(e,t)=>{this.mutate(e,t).catch(()=>{})},mutateAsync:(e,t)=>this.mutate(e,t),reset:()=>{this.mutation.state=this.createInitialResult(),this.updateResult()}}}updateResult(){this.currentResult=this.createResult(),this.subscribers.forEach(e=>e(this.currentResult))}}class K extends b{constructor(e,t){super(e,t),this.infiniteOptions=t}async fetchNextPage(e){return this.getCurrentResult()}async fetchPreviousPage(e){return this.getCurrentResult()}getCurrentResult(){const e=super.getCurrentResult(),t=e.data;return{...e,fetchNextPage:this.fetchNextPage.bind(this),fetchPreviousPage:this.fetchPreviousPage.bind(this),hasNextPage:this.hasNextPage(t),hasPreviousPage:this.hasPreviousPage(t),isFetchingNextPage:!1,isFetchingPreviousPage:!1}}hasNextPage(e){if(!e||!e.pages.length)return!1;const t=e.pages[e.pages.length-1],s=this.infiniteOptions.getNextPageParam(t,e.pages);return s!=null}hasPreviousPage(e){if(!e||!e.pages.length||!this.infiniteOptions.getPreviousPageParam)return!1;const t=e.pages[0],s=this.infiniteOptions.getPreviousPageParam(t,e.pages);return s!=null}}class M{constructor(e,t,s){this.observers=[],this.subscribers=new Set,this.client=e,this.options=s||{queries:t},this.observers=t.map(r=>{const i=e.defaultQueryOptions(r);return new b(e,i)}),this.currentResult=this.getCombinedResult()}subscribe(e){this.subscribers.add(e),e(this.currentResult);const t=this.observers.map(s=>s.subscribe(()=>{this.currentResult=this.getCombinedResult(),this.subscribers.forEach(r=>r(this.currentResult))}));return()=>{this.subscribers.delete(e),t.forEach(s=>s())}}getOptimisticResult(e,t){const s=e.map(i=>{const o=this.client.defaultQueryOptions(i);return new b(this.client,o).getCurrentResult()}),r=t||this.options.combine||(i=>i);return[s,r]}setQueries(e,t){this.options=t||{queries:e},this.observers=e.map(s=>{const r=this.client.defaultQueryOptions(s);return new b(this.client,r)}),this.currentResult=this.getCombinedResult(),this.subscribers.forEach(s=>s(this.currentResult))}getCombinedResult(){const e=this.observers.map(s=>s.getCurrentResult());return(this.options.combine||(s=>s))(e)}}const I="VUE_QUERY_CLIENT";function F(u){const e=u?`:${u}`:"";return`${I}${e}`}function v(u,e){Object.keys(u).forEach(t=>{u[t]=e[t]})}function R(u,e,t="",s=0){if(e){const r=e(u,t,s);if(r===void 0&&n.isRef(u)||r!==void 0)return r}if(Array.isArray(u))return u.map((r,i)=>R(r,e,String(i),s+1));if(typeof u=="object"&&H(u)){const r=Object.entries(u).map(([i,o])=>[i,R(o,e,i,s+1)]);return Object.fromEntries(r)}return u}function L(u,e){return R(u,e)}function a(u,e=!1){return L(u,(t,s,r)=>{if(r===1&&s==="queryKey")return a(t,!0);if(e&&J(t))return a(t(),e);if(n.isRef(t))return a(n.unref(t),e)})}function H(u){if(Object.prototype.toString.call(u)!=="[object Object]")return!1;const e=Object.getPrototypeOf(u);return e===null||e===Object.prototype}function J(u){return typeof u=="function"}function p(u=""){if(!n.hasInjectionContext())throw new Error("vue-query hooks can only be used inside setup() function or functions that support injection context.");const e=F(u),t=n.inject(e);if(!t)throw new Error("No 'queryClient' found in Vue context, use 'VueQueryPlugin' to properly initialize the library.");return t}class U extends D{find(e){return super.find(a(e))}findAll(e={}){return super.findAll(a(e))}}class N extends P{find(e){return super.find(a(e))}findAll(e={}){return super.findAll(a(e))}}class x extends V{constructor(e={}){const t={defaultOptions:e.defaultOptions,queryCache:e.queryCache||new U,mutationCache:e.mutationCache||new N};super(t)}isFetching(e={}){return super.isFetching(a(e))}isMutating(e={}){return super.isMutating(a(e))}getQueryData(e){return super.getQueryData(a(e))}ensureQueryData(e){return super.ensureQueryData(a(e))}getQueriesData(e){return super.getQueriesData(a(e))}setQueryData(e,t,s={}){return super.setQueryData(a(e),t,a(s))}setQueriesData(e,t,s={}){return super.setQueriesData(a(e),t,a(s))}getQueryState(e){return super.getQueryState(a(e))}removeQueries(e={}){return super.removeQueries(a(e))}resetQueries(e={},t={}){return super.resetQueries(a(e),a(t))}cancelQueries(e={},t={}){return super.cancelQueries(a(e),a(t))}invalidateQueries(e={},t={}){const s=a(e),r=a(t);if(super.invalidateQueries({...s,refetchType:"none"},r),s.refetchType==="none")return Promise.resolve();const i={...s,type:s.refetchType??s.type??"active"};return n.nextTick().then(()=>super.refetchQueries(i,r))}refetchQueries(e={},t={}){return super.refetchQueries(a(e),a(t))}fetchQuery(e){return super.fetchQuery(a(e))}prefetchQuery(e){return super.prefetchQuery(a(e))}fetchInfiniteQuery(e){return super.fetchInfiniteQuery(a(e))}prefetchInfiniteQuery(e){return super.prefetchInfiniteQuery(a(e))}setDefaultOptions(e){super.setDefaultOptions(a(e))}setQueryDefaults(e,t){const s=a(e),r=a(t);super.setQueryDefaults(s,r)}getQueryDefaults(e){return super.getQueryDefaults(a(e))}setMutationDefaults(e,t){super.setMutationDefaults(a(e),a(t))}getMutationDefaults(e){return super.getMutationDefaults(a(e))}}const T={install:(u,e={})=>{var o;const t=F(e.queryClientKey);let s;if("queryClient"in e&&e.queryClient)s=e.queryClient;else{const l="queryClientConfig"in e?e.queryClientConfig:void 0;s=new x(l)}if(e.refetchOnShow!==!1&&typeof uni<"u"&&uni.onShow){const l=()=>{s.refetchQueries({type:"active"}).catch(()=>{})};uni.onShow(l)}const i=()=>{};(o=u.onUnmount)==null||o.call(u,i),u.provide(t,s)}};function $(u){return u}function k(u){return u}function j(u,e,t){process.env.NODE_ENV==="development"&&(n.getCurrentScope()||console.warn('vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.'));const s=t||p(),r=n.computed(()=>{let c=e;typeof c=="function"&&(c=c());const m=a(c);typeof m.enabled=="function"&&(m.enabled=m.enabled());const Q=s.defaultQueryOptions(m);return Q._optimisticResults="optimistic",Q}),i=new u(s,r.value),o=r.value.shallow?n.shallowReactive(i.getCurrentResult()):n.reactive(i.getCurrentResult());let l=()=>{};l=i.subscribe(c=>{v(o,c)});const d=()=>{i.setOptions(r.value),v(o,i.getCurrentResult())};n.watch(r,d),n.onScopeDispose(()=>{l()});const g=(...c)=>(d(),o.refetch(...c)),y=()=>new Promise((c,m)=>{let Q=()=>{};const w=()=>{if(r.value.enabled!==!1){i.setOptions(r.value);const O=i.getOptimisticResult(r.value);O.isStale?(Q(),i.fetchOptimistic(r.value).then(c,S=>{q(r.value.throwOnError,[S,i.getCurrentQuery()])?m(S):c(i.getCurrentResult())})):(Q(),c(O))}};w(),Q=n.watch(r,w)});n.watch(()=>o.error,c=>{if(o.isError&&!o.isFetching&&q(r.value.throwOnError,[c,i.getCurrentQuery()]))throw c});const h=r.value.shallow?n.shallowReadonly(o):n.readonly(o),f=n.toRefs(h);for(const c in o)typeof o[c]=="function"&&(f[c]=o[c]);return f.suspense=y,f.refetch=g,f}function W(u,e){return j(b,u,e)}function Y({queries:u,...e},t){process.env.NODE_ENV==="development"&&(n.getCurrentScope()||console.warn('vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.'));const s=t||p(),r=n.computed(()=>{const d=typeof u=="function"?u():u;return n.unref(d).map(y=>{const h=a(y);typeof h.enabled=="function"&&(h.enabled=y.enabled());const f=s.defaultQueryOptions(h);return f._optimisticResults="optimistic",f})}),i=new M(s,r.value,e),o=()=>{const[d,g]=i.getOptimisticResult(r.value,e.combine);return g(d.map((y,h)=>({...y,refetch:async(...f)=>{const[{[h]:c}]=i.getOptimisticResult(r.value,e.combine);return c.refetch(...f)}})))},l=n.shallowRef(o());return n.watch(r,d=>{i.setQueries(d,e),l.value=o()}),n.onScopeDispose(()=>{}),e.shallow?n.shallowReadonly(l):n.readonly(l)}function B(u,e){return j(K,u,e)}function X(u,e){process.env.NODE_ENV==="development"&&(n.getCurrentScope()||console.warn('vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.'));const t=e||p(),s=n.computed(()=>{const h=typeof u=="function"?u():u;return t.defaultMutationOptions(a(h))}),r=new A(t,s.value),i=s.value.shallow??!1,o=i?n.shallowReactive(r.getCurrentResult()):n.reactive(r.getCurrentResult()),l=r.subscribe(h=>{v(o,h)}),d=(h,f)=>{r.mutate(h,f).catch(()=>{})};n.watch(s,()=>{r.setOptions(s.value)}),n.onScopeDispose(()=>{l()});const g=i?n.shallowReadonly(o):n.readonly(o),y=n.toRefs(g);return n.watch(()=>o.error,h=>{if(h&&q(s.value.throwOnError,[h,void 0]))throw h}),{...y,mutate:d,mutateAsync:o.mutateAsync,reset:o.reset}}function Z(u={},e){process.env.NODE_ENV==="development"&&(n.getCurrentScope()||console.warn('vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.'));const t=e||p(),s=n.ref(),r=()=>{const o=typeof u=="function"?u():u;s.value=t.isFetching(a(o))},i=t.queryCache.subscribe(r);return n.watchEffect(r),n.onScopeDispose(()=>{i()}),s}function z(u={},e){process.env.NODE_ENV==="development"&&(n.getCurrentScope()||console.warn('vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.'));const t=e||p(),s=_({filters:n.computed(()=>({...a(typeof u=="function"?u():u),status:"pending"}))},t);return n.computed(()=>s.value.length)}function C(u,e){return u.findAll(e.filters).map(t=>e.select?e.select(t):t.state)}function _(u={},e){const t=n.computed(()=>{const o=typeof u=="function"?u():u;return{filters:a(o.filters),select:o.select}}),s=(e||p()).mutationCache,r=n.shallowRef(C(s,t.value)),i=s.subscribe(()=>{r.value=C(s,t.value)});return n.watch(t,()=>{r.value=C(s,t.value)}),n.onScopeDispose(()=>{i()}),n.shallowReadonly(r)}exports.InfiniteQueryObserver=K;exports.MutationCache=N;exports.MutationObserver=A;exports.QueriesObserver=M;exports.QueryCache=U;exports.QueryClient=x;exports.QueryObserver=b;exports.UniQueryPlugin=T;exports.VUE_QUERY_CLIENT=I;exports.VueQueryPlugin=T;exports.hashQueryKey=E;exports.infiniteQueryOptions=k;exports.queryOptions=$;exports.shouldThrowError=q;exports.useInfiniteQuery=B;exports.useIsFetching=Z;exports.useIsMutating=z;exports.useMutation=X;exports.useMutationState=_;exports.useQueries=Y;exports.useQuery=W;exports.useQueryClient=p;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export * from './query-core';
|
|
2
|
+
export { useQueryClient } from './useQueryClient';
|
|
3
|
+
export { VueQueryPlugin } from './vueQueryPlugin';
|
|
4
|
+
export { VueQueryPlugin as UniQueryPlugin } from './vueQueryPlugin';
|
|
5
|
+
export { QueryClient } from './queryClient';
|
|
6
|
+
export { QueryCache } from './queryCache';
|
|
7
|
+
export { queryOptions } from './queryOptions';
|
|
8
|
+
export { infiniteQueryOptions } from './infiniteQueryOptions';
|
|
9
|
+
export type { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions, } from './infiniteQueryOptions';
|
|
10
|
+
export { MutationCache } from './mutationCache';
|
|
11
|
+
export { useQuery } from './useQuery';
|
|
12
|
+
export { useQueries } from './useQueries';
|
|
13
|
+
export { useInfiniteQuery } from './useInfiniteQuery';
|
|
14
|
+
export { useMutation } from './useMutation';
|
|
15
|
+
export { useIsFetching } from './useIsFetching';
|
|
16
|
+
export { useIsMutating, useMutationState } from './useMutationState';
|
|
17
|
+
export { VUE_QUERY_CLIENT } from './utils';
|
|
18
|
+
export type { UseQueryOptions, UseQueryReturnType, UseQueryDefinedReturnType, UndefinedInitialQueryOptions, DefinedInitialQueryOptions, } from './useQuery';
|
|
19
|
+
export type { UseInfiniteQueryOptions, UseInfiniteQueryReturnType, } from './useInfiniteQuery';
|
|
20
|
+
export type { UseMutationOptions, UseMutationReturnType } from './useMutation';
|
|
21
|
+
export type { UseQueriesOptions, UseQueriesResults } from './useQueries';
|
|
22
|
+
export type { MutationFilters, MutationStateOptions } from './useMutationState';
|
|
23
|
+
export type { QueryFilters } from './useIsFetching';
|
|
24
|
+
export type { VueQueryPluginOptions } from './vueQueryPlugin';
|