-
-
Notifications
You must be signed in to change notification settings - Fork 337
/
Copy pathshared.ts
317 lines (278 loc) · 8.05 KB
/
shared.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import { DatabaseReference, Query as DatabaseQuery } from 'firebase/database'
import type {
CollectionReference,
DocumentData,
DocumentReference,
Query as FirestoreQuery,
} from 'firebase/firestore'
import { StorageReference } from 'firebase/storage'
import { getCurrentInstance, inject, isVue2 } from 'vue-demi'
import type { Ref, ShallowRef } from 'vue-demi'
export const noop = () => {}
export const isClient = typeof window !== 'undefined'
export interface OperationsType {
set<T extends object = Record<any, unknown>>(
target: T,
// accepts a dot delimited path
path: string | number,
value: T[any]
): T[any] | T[any][]
add<T extends unknown = unknown>(array: T[], index: number, data: T): T[]
remove<T extends unknown = unknown>(array: T[], index: number): T[]
}
/**
* Allow resetting a subscription vue ref when the source changes or is removed. `false` keeps the value as is while
* true resets it to `null` for objects and `[]` for arrays. A function allows to specify a custom reset value.
*/
export type ResetOption = boolean | (() => unknown)
/**
* Flattens out a type.
*
* @internal
*/
export type _Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {}
/**
* Return type of `$databaseBind()` and `$firestoreBind()`
*/
export type UnbindWithReset = (reset?: ResetOption) => void
/**
* @internal
*/
export type _Nullable<T> = T | null | undefined
export type TODO = any
/**
* Walks a path inside an object
* walkGet({ a: { b: true }}), 'a.b') -> true
* @param obj
* @param path
*/
export function walkGet(obj: Record<string, TODO>, path: string): TODO {
return path.split('.').reduce((target, key) => target && target[key], obj)
}
/**
* Deeply set a property in an object with a string path
* walkSet({ a: { b: true }}, 'a.b', false)
* @param obj
* @param path
* @param value
* @returns an array with the element that was replaced or the value that was set
*/
export function walkSet<T extends object = Record<any, unknown>>(
obj: T,
path: string | number,
value: T[any]
): T[any] | T[any][] {
// path can be a number
const keys = ('' + path).split('.') as Array<keyof T>
// slipt produces at least one element
const key = keys.pop()!
const target = keys.reduce(
(target, key) =>
// @ts-expect-error: FIXME: maybe
target && target[key],
obj
)
if (target == null) return
return Array.isArray(target)
? target.splice(Number(key), 1, value)
: // @ts-expect-error: FIXME: maybe
(target[key] =
//
value)
}
/**
* Checks if a variable is an object
* @param o
*/
export function isObject(o: unknown): o is Record<any, unknown> {
return !!o && typeof o === 'object'
}
const ObjectPrototype = Object.prototype
/**
* Check if an object is a plain js object. Differently from `isObject()`, this excludes class instances.
*
* @param obj - object to check
*/
export function isPOJO(obj: unknown): obj is Record<any, unknown> {
return isObject(obj) && Object.getPrototypeOf(obj) === ObjectPrototype
}
/**
* Checks if a variable is a Firestore Document Reference
* @param o
*/
export function isDocumentRef<T = DocumentData>(
o: unknown
): o is DocumentReference<T> {
return isObject(o) && o.type === 'document'
}
/**
* Checks if a variable is a Firestore Collection Reference
* @param o
*/
export function isCollectionRef<T = DocumentData>(
o: unknown
): o is CollectionReference<T> {
return isObject(o) && o.type === 'collection'
}
export function isFirestoreDataReference<T = unknown>(
source: unknown
): source is CollectionReference<T> | DocumentReference<T> {
return isDocumentRef(source) || isCollectionRef(source)
}
export function isFirestoreQuery<
AppModelType = DocumentData,
DbModelType extends DocumentData = DocumentData,
>(
source: unknown
): source is FirestoreQuery<AppModelType, DbModelType> & { path: undefined } {
// makes some types so much easier
return isObject(source) && source.type === 'query'
}
export function getDataSourcePath(
source:
| DocumentReference<unknown>
| FirestoreQuery<unknown>
| CollectionReference<unknown>
| DatabaseQuery
): string | null {
return isFirestoreDataReference(source)
? source.path
: isDatabaseReference(source)
? // gets a path like /users/1?orderByKey=true
source.toString()
: isFirestoreQuery(source)
? // internal id
null // FIXME: find a way to get the canonicalId that no longer exists
: null
}
export function isDatabaseReference(
source: unknown
): source is DatabaseReference | DatabaseQuery {
return isObject(source) && 'ref' in source
}
export function isStorageReference(
source: unknown
): source is StorageReference {
return isObject(source) && typeof source.bucket === 'string'
}
/**
* Wraps a function so it gets called only once
* @param fn Function to be called once
* @param argFn Function to compute the argument passed to fn
*/
export function callOnceWithArg<T, K>(
fn: (arg: T) => K,
argFn: () => T
): () => K | undefined {
let called: boolean | undefined
return (): K | undefined => {
if (!called) {
called = true
return fn(argFn())
}
}
}
export type _FirestoreDataSource =
| DocumentReference<unknown>
| CollectionReference<unknown>
| FirestoreQuery<unknown>
/**
* @internal
*/
export interface _RefWithState<T, E = Error> extends Ref<T> {
/**
* Realtime data wrapped in a Vue `ref`
*/
get data(): Ref<T>
/**
* Reactive Error if the firebase operation fails
*/
get error(): Ref<E | undefined>
/**
* Reactive loading state
*/
get pending(): Ref<boolean>
/**
* Reactive promise that resolves when the data is loaded or rejects if there is an error
*/
get promise(): ShallowRef<Promise<T>>
/**
* Stops listening to the data changes and stops the Vue watcher.
*/
stop: (reset?: ResetOption) => void
}
/**
* Base options for the data source options in both Firestore and Realtime Database.
*
* @internal
*/
export interface _DataSourceOptions<DataT = unknown> {
/**
* Use the `target` ref instead of creating one.
*/
target?: Ref<DataT>
/**
* Optional key to handle SSR hydration. **Necessary for Queries** or when the same source is used in multiple places
* with different converters.
*/
ssrKey?: string
/**
* If true, the data will be reset when the data source is unbound. Pass a function to specify a custom reset value.
*/
reset?: ResetOption
/**
* If true, wait until the data is loaded before setting the data for the first time. For Firestore, this includes
* nested refs. This is only useful for lists and collections. Objects and documents do not need this.
*/
wait?: boolean
/**
* Should the data be fetched once rather than subscribing to changes.
*/
once?: boolean
}
/**
* Make all properties in T writable.
*/
export type _Mutable<T> = {
-readonly [P in keyof T]: T[P]
}
/**
* helper type to get the type of a promise
*
* @internal
*/
export interface _ResolveRejectFn {
(value: unknown): void
}
// NOTE: copied from vue core, avoids importing it since it only exists in Vue 3
const ssrContextKey = Symbol.for('v-scx')
/**
* Check if we are in an SSR environment within a composable. Used to force `options.once` to `true`.
*
* @internal
*/
export function useIsSSR(): boolean {
const instance = getCurrentInstance()
return !!(isVue2
? instance &&
// @ts-expect-error: Vue 2 only API
(instance.proxy.$isServer as boolean)
: inject(ssrContextKey, 0))
}
/**
* Checks and warns if a data ref has already bee overwritten by useDocument() and others.
*
* @internal
*/
export function checkWrittenTarget(
data: Ref<unknown>,
fnName: string
): boolean {
if (Object.getOwnPropertyDescriptor(data, 'data')?.get?.() === data) {
console.warn(`[VueFire] the passed "options.target" is already the returned value of "${fnName}". If you want to subscribe to a different data source, pass a reactive variable to "${fnName}" instead:
https://vuefire.vuejs.org/guide/realtime-data.html#declarative-realtime-data
This will FAIL in production.`)
return true
}
return false
}