/
StorageFileApi.ts
394 lines (372 loc) · 12.5 KB
/
StorageFileApi.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import { Fetch, FetchParameters, get, post, remove } from './fetch'
import { resolveFetch } from './helpers'
import { FileObject, FileOptions, SearchOptions } from './types'
const DEFAULT_SEARCH_OPTIONS = {
limit: 100,
offset: 0,
sortBy: {
column: 'name',
order: 'asc',
},
}
const DEFAULT_FILE_OPTIONS: FileOptions = {
cacheControl: '3600',
contentType: 'text/plain;charset=UTF-8',
upsert: false,
}
export class StorageFileApi {
protected url: string
protected headers: { [key: string]: string }
protected bucketId?: string
protected fetch: Fetch
constructor(
url: string,
headers: { [key: string]: string } = {},
bucketId?: string,
fetch?: Fetch
) {
this.url = url
this.headers = headers
this.bucketId = bucketId
this.fetch = resolveFetch(fetch)
}
/**
* Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.
*
* @param method HTTP method.
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
* @param fileOptions HTTP headers.
* `cacheControl`: string, the `Cache-Control: max-age=<seconds>` seconds value.
* `contentType`: string, the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`.
* `upsert`: boolean, whether to perform an upsert.
*/
private async uploadOrUpdate(
method: 'POST' | 'PUT',
path: string,
fileBody:
| ArrayBuffer
| ArrayBufferView
| Blob
| Buffer
| File
| FormData
| NodeJS.ReadableStream
| ReadableStream<Uint8Array>
| URLSearchParams
| string,
fileOptions?: FileOptions
): Promise<{ data: { Key: string } | null; error: Error | null }> {
try {
let body
const options = { ...DEFAULT_FILE_OPTIONS, ...fileOptions }
const headers: Record<string, string> = {
...this.headers,
...(method === 'POST' && { 'x-upsert': String(options.upsert as boolean) }),
}
if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
body = new FormData()
body.append('cacheControl', options.cacheControl as string)
body.append('', fileBody)
} else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
body = fileBody
body.append('cacheControl', options.cacheControl as string)
} else {
body = fileBody
headers['cache-control'] = `max-age=${options.cacheControl}`
headers['content-type'] = options.contentType as string
}
const cleanPath = this._removeEmptyFolders(path)
const _path = this._getFinalPath(cleanPath)
const res = await this.fetch(`${this.url}/object/${_path}`, {
method,
body: body as BodyInit,
headers,
})
if (res.ok) {
// const data = await res.json()
// temporary fix till backend is updated to the latest storage-api version
return { data: { Key: _path }, error: null }
} else {
const error = await res.json()
return { data: null, error }
}
} catch (error) {
return { data: null, error }
}
}
/**
* Uploads a file to an existing bucket.
*
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
* @param fileOptions HTTP headers.
* `cacheControl`: string, the `Cache-Control: max-age=<seconds>` seconds value.
* `contentType`: string, the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`.
* `upsert`: boolean, whether to perform an upsert.
*/
async upload(
path: string,
fileBody:
| ArrayBuffer
| ArrayBufferView
| Blob
| Buffer
| File
| FormData
| NodeJS.ReadableStream
| ReadableStream<Uint8Array>
| URLSearchParams
| string,
fileOptions?: FileOptions
): Promise<{ data: { Key: string } | null; error: Error | null }> {
return this.uploadOrUpdate('POST', path, fileBody, fileOptions)
}
/**
* Replaces an existing file at the specified path with a new one.
*
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
* @param fileOptions HTTP headers.
* `cacheControl`: string, the `Cache-Control: max-age=<seconds>` seconds value.
* `contentType`: string, the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`.
* `upsert`: boolean, whether to perform an upsert.
*/
async update(
path: string,
fileBody:
| ArrayBuffer
| ArrayBufferView
| Blob
| Buffer
| File
| FormData
| NodeJS.ReadableStream
| ReadableStream<Uint8Array>
| URLSearchParams
| string,
fileOptions?: FileOptions
): Promise<{ data: { Key: string } | null; error: Error | null }> {
return this.uploadOrUpdate('PUT', path, fileBody, fileOptions)
}
/**
* Moves an existing file.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-new.png`.
*/
async move(
fromPath: string,
toPath: string
): Promise<{ data: { message: string } | null; error: Error | null }> {
try {
const data = await post(
this.fetch,
`${this.url}/object/move`,
{ bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath },
{ headers: this.headers }
)
return { data, error: null }
} catch (error) {
return { data: null, error }
}
}
/**
* Copies an existing file.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.
*/
async copy(
fromPath: string,
toPath: string
): Promise<{ data: { message: string } | null; error: Error | null }> {
try {
const data = await post(
this.fetch,
`${this.url}/object/copy`,
{ bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath },
{ headers: this.headers }
)
return { data, error: null }
} catch (error) {
return { data: null, error }
}
}
/**
* Create signed URL to download file without requiring permissions. This URL can be valid for a set number of seconds.
*
* @param path The file path to be downloaded, including the current file name. For example `folder/image.png`.
* @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.
*/
async createSignedUrl(
path: string,
expiresIn: number
): Promise<{
data: { signedURL: string } | null
error: Error | null
signedURL: string | null
}> {
try {
const _path = this._getFinalPath(path)
let data = await post(
this.fetch,
`${this.url}/object/sign/${_path}`,
{ expiresIn },
{ headers: this.headers }
)
const signedURL = `${this.url}${data.signedURL}`
data = { signedURL }
return { data, error: null, signedURL }
} catch (error) {
return { data: null, error, signedURL: null }
}
}
/**
* Create signed URLs to download files without requiring permissions. These URLs can be valid for a set number of seconds.
*
* @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.
* @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.
*/
async createSignedUrls(
paths: string[],
expiresIn: number
): Promise<{
data: { error: string | null; path: string | null; signedURL: string }[] | null
error: Error | null
}> {
try {
const data = await post(
this.fetch,
`${this.url}/object/sign/${this.bucketId}`,
{ expiresIn, paths },
{ headers: this.headers }
)
return {
data: data.map((datum: { signedURL: string }) => ({
...datum,
signedURL: datum.signedURL ? `${this.url}${datum.signedURL}` : null,
})),
error: null,
}
} catch (error) {
return { data: null, error }
}
}
/**
* Downloads a file.
*
* @param path The file path to be downloaded, including the path and file name. For example `folder/image.png`.
*/
async download(path: string): Promise<{ data: Blob | null; error: Error | null }> {
try {
const _path = this._getFinalPath(path)
const res = await get(this.fetch, `${this.url}/object/${_path}`, {
headers: this.headers,
noResolveJson: true,
})
const data = await res.blob()
return { data, error: null }
} catch (error) {
return { data: null, error }
}
}
/**
* Retrieve URLs for assets in public buckets
*
* @param path The file path to be downloaded, including the path and file name. For example `folder/image.png`.
*/
getPublicUrl(
path: string
): {
data: { publicURL: string } | null
error: Error | null
publicURL: string | null
} {
try {
const _path = this._getFinalPath(path)
const publicURL = `${this.url}/object/public/${_path}`
const data = { publicURL }
return { data, error: null, publicURL }
} catch (error) {
return { data: null, error, publicURL: null }
}
}
/**
* Deletes files within the same bucket
*
* @param paths An array of files to be deleted, including the path and file name. For example [`folder/image.png`].
*/
async remove(paths: string[]): Promise<{ data: FileObject[] | null; error: Error | null }> {
try {
const data = await remove(
this.fetch,
`${this.url}/object/${this.bucketId}`,
{ prefixes: paths },
{ headers: this.headers }
)
return { data, error: null }
} catch (error) {
return { data: null, error }
}
}
/**
* Get file metadata
* @param id the file id to retrieve metadata
*/
// async getMetadata(id: string): Promise<{ data: Metadata | null; error: Error | null }> {
// try {
// const data = await get(`${this.url}/metadata/${id}`, { headers: this.headers })
// return { data, error: null }
// } catch (error) {
// return { data: null, error }
// }
// }
/**
* Update file metadata
* @param id the file id to update metadata
* @param meta the new file metadata
*/
// async updateMetadata(
// id: string,
// meta: Metadata
// ): Promise<{ data: Metadata | null; error: Error | null }> {
// try {
// const data = await post(`${this.url}/metadata/${id}`, { ...meta }, { headers: this.headers })
// return { data, error: null }
// } catch (error) {
// return { data: null, error }
// }
// }
/**
* Lists all the files within a bucket.
* @param path The folder path.
* @param options Search options, including `limit`, `offset`, and `sortBy`.
* @param parameters Fetch parameters, currently only supports `signal`, which is an AbortController's signal
*/
async list(
path?: string,
options?: SearchOptions,
parameters?: FetchParameters
): Promise<{ data: FileObject[] | null; error: Error | null }> {
try {
const body = { ...DEFAULT_SEARCH_OPTIONS, ...options, prefix: path || '' }
const data = await post(
this.fetch,
`${this.url}/object/list/${this.bucketId}`,
body,
{ headers: this.headers },
parameters
)
return { data, error: null }
} catch (error) {
return { data: null, error }
}
}
_getFinalPath(path: string) {
return `${this.bucketId}/${path}`
}
_removeEmptyFolders(path: string) {
return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/')
}
}