forked from vuejs/vuefire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
313 lines (277 loc) · 7.48 KB
/
index.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
import {
getStorage,
StorageReference,
updateMetadata,
uploadBytesResumable,
deleteObject,
getDownloadURL,
getMetadata,
UploadMetadata,
UploadTask,
UploadTaskSnapshot,
StorageError,
SettableMetadata,
FullMetadata,
} from 'firebase/storage'
import {
computed,
getCurrentInstance,
getCurrentScope,
isRef,
onScopeDispose,
onServerPrefetch,
ref,
shallowRef,
toValue,
watch,
MaybeRefOrGetter,
} from 'vue-demi'
import { useFirebaseApp } from '../app'
import { noop, _Nullable } from '../shared'
import { getInitialValue } from '../ssr/initialState'
import { addPendingPromise } from '../ssr/plugin'
/**
* Retrieves the Storage instance.
*
* @param name - name of the application
* @returns the Database instance
*/
export function useFirebaseStorage(name?: string) {
return getStorage(useFirebaseApp(name))
}
/**
* Retrieves a reactive download URL of a `StorageReference`. Updates automatically if the `StorageReference` changes.
*
* @param storageRef - StorageReference
*/
export function useStorageFileUrl(
storageRef: MaybeRefOrGetter<_Nullable<StorageReference>>
) {
const initialSourceValue = toValue(storageRef)
const url = ref<string | null>()
url.value = getInitialValue(
initialSourceValue,
undefined,
url.value,
useFirebaseApp()
) as string
const promise = shallowRef<Promise<string | null>>(Promise.resolve(null))
// TODO: pending and error states?
let removePendingPromise = noop
function refresh() {
const storageSource = toValue(storageRef)
if (storageSource) {
promise.value = getDownloadURL(storageSource)
.then((downloadUrl) => (url.value = downloadUrl))
// TODO: refactor with error states
.catch(() => null)
} else {
promise.value = Promise.resolve((url.value = null))
}
return promise.value
}
refresh()
if (isRef(storageRef) || typeof storageRef === 'function') {
watch(storageRef, refresh)
}
// SSR
if (initialSourceValue) {
removePendingPromise = addPendingPromise(promise.value, initialSourceValue)
}
if (getCurrentScope()) {
onScopeDispose(removePendingPromise)
}
if (getCurrentInstance()) {
onServerPrefetch(() => promise.value)
}
return { url, refresh, promise }
}
/**
* Returns a reactive version of the metadata of a `StorageReference`. Updates automatically if the `StorageReference`
* changes.
*
* @param storageRef - StorageReference
*/
export function useStorageFileMetadata(
storageRef: MaybeRefOrGetter<_Nullable<StorageReference>>
) {
const initialSourceValue = toValue(storageRef)
const metadata = shallowRef<FullMetadata | null>()
if (initialSourceValue) {
metadata.value = getInitialValue(
initialSourceValue,
// 'm ' is a prefix to differentiate from urls since both are stored in the same object
'm ' + initialSourceValue.toString(),
metadata.value,
useFirebaseApp()
) as FullMetadata
}
const promise = shallowRef<Promise<FullMetadata | null>>(
Promise.resolve(null)
)
let removePendingPromise = noop
function refresh() {
const storageSource = toValue(storageRef)
if (storageSource) {
promise.value = getMetadata(storageSource)
.then((data) => (metadata.value = data))
// TODO: refactor with error states
.catch(() => null)
} else {
promise.value = Promise.resolve((metadata.value = null))
}
return promise.value
}
function update(newMetadata: SettableMetadata) {
const storageSource = toValue(storageRef)
if (storageSource) {
promise.value = updateMetadata(storageSource, newMetadata).then(
(newData) => {
return (metadata.value = newData)
}
)
} else if (process.env.NODE_ENV !== 'production') {
console.warn('[VueFire]: "update()" called with no storage source.')
}
return promise.value
}
refresh()
if (isRef(storageRef)) {
watch(storageRef, refresh)
}
// SSR
if (initialSourceValue) {
removePendingPromise = addPendingPromise(promise.value, initialSourceValue)
}
if (getCurrentScope()) {
onScopeDispose(removePendingPromise)
}
if (getCurrentInstance()) {
onServerPrefetch(() => promise.value)
}
return { metadata, update, refresh, promise }
}
/**
* Reactive information (url, metadata) of a `StorageReference`. Allows updating and deleting the storage object.
*
* @param storageRef - StorageReference
*/
export function useStorageFile(
storageRef: MaybeRefOrGetter<_Nullable<StorageReference>>
) {
const { url, refresh: refreshUrl } = useStorageFileUrl(storageRef)
const {
metadata,
update: updateMetadata,
refresh: refreshMetadata,
} = useStorageFileMetadata(storageRef)
const uploadTask = shallowRef<UploadTask | null>()
const snapshot = shallowRef<UploadTaskSnapshot | null>()
const uploadError = shallowRef<StorageError | null>()
const uploadProgress = computed(() => {
const snap = toValue(snapshot)
return snap ? snap.bytesTransferred / snap.totalBytes : null
})
// unsubscribe from the task
let unsub = noop
function upload(
newData: Blob | Uint8Array | ArrayBuffer,
newMetadata?: UploadMetadata
) {
const storageSource = toValue(storageRef)
const currentTask = toValue(uploadTask)
// cancel previous task
if (currentTask) {
currentTask.cancel()
}
uploadError.value = null
snapshot.value = null
uploadTask.value = null
url.value = null
metadata.value = null
unsub()
if (storageSource) {
const newTask = uploadBytesResumable(storageSource, newData, newMetadata)
uploadTask.value = newTask
snapshot.value = newTask.snapshot
unsub = newTask.on('state_changed', (newSnapshot) => {
snapshot.value = newSnapshot
})
return newTask
.then((finalSnapshot) => {
metadata.value = finalSnapshot.metadata
// get the new download URL
refreshUrl()
})
.catch((err) => {
uploadError.value = err
// propagate the error
return Promise.reject(err)
})
.finally(() => {
unsub()
uploadTask.value = null
})
}
}
function _deleteObject() {
const storageSource = toValue(storageRef)
if (storageSource) {
deleteObject(storageSource)
metadata.value = null
url.value = null
unsub()
snapshot.value = null
uploadTask.value = null
}
}
function refresh() {
return Promise.all([refreshUrl(), refreshMetadata()])
}
if (isRef(storageRef) || typeof storageRef === 'function') {
watch(storageRef, (storageSource) => {
if (!storageSource) {
if (uploadTask.value) {
unsub()
uploadTask.value.cancel()
}
uploadTask.value = null
snapshot.value = null
}
refresh()
})
}
// remove the task subscription
if (getCurrentScope()) {
onScopeDispose(unsub)
}
return {
url,
metadata,
snapshot,
uploadTask,
uploadError,
uploadProgress,
upload,
updateMetadata,
refresh,
// promise,
}
}
// DEPRECATION
/**
* @deprecated use `useFirebaseStorage()` instead
*/
export const useStorage = useFirebaseStorage
/**
* @deprecated use `useStorageFileUrl()` instead
*/
export const useStorageUrl = useStorageFileUrl
/**
* @deprecated use `useStorageFileMetadata()` instead
*/
export const useStorageMetadata = useStorageFileMetadata
/**
* @deprecated use `useStorageFile()` instead
*/
export const useStorageObject = useStorageFile