/
StorageFileApi.ts
246 lines (224 loc) · 7.35 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
import { get, post, remove } from './fetch'
import { isBrowser } from './helpers'
import { FileObject, FileOptions, Metadata, SearchOptions } from './types'
const DEFAULT_SEARCH_OPTIONS = {
limit: 0,
offset: 0,
sortBy: {
column: 'name',
order: 'asc',
},
}
const DEFAULT_FILE_OPTIONS: FileOptions = {
cacheControl: '3600',
}
export class StorageFileApi {
protected url: string
protected headers: { [key: string]: string }
protected bucketId?: string
constructor(url: string, headers: { [key: string]: string } = {}, bucketId?: string) {
this.url = url
this.headers = headers
this.bucketId = bucketId
}
/**
* Uploads a file to an existing bucket.
*
* @param path The relative file path including the bucket ID. Should be of the format `bucket/folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param file The File object to be stored in the bucket.
* @param fileOptions HTTP headers. For example `cacheControl`
*/
async upload(
path: string,
file: File,
fileOptions?: FileOptions
): Promise<{ data: { message: string } | null; error: Error | null }> {
try {
if (!isBrowser()) throw new Error('No browser detected.')
const formData = new FormData()
formData.append('', file, file.name)
const options = { ...DEFAULT_FILE_OPTIONS, ...fileOptions }
formData.append('cacheControl', options.cacheControl)
const _path = this._getFinalPath(path)
const res = await fetch(`${this.url}/object/${_path}`, {
method: 'POST',
body: formData,
headers: { ...this.headers },
})
if (res.ok) {
const data = await res.json()
return { data, error: null }
} else {
const error = await res.json()
return { data: null, error }
}
} catch (error) {
return { data: null, error }
}
}
/**
* Replaces an existing file at the specified path with a new one.
*
* @param path The relative file path including the bucket ID. Should be of the format `bucket/folder/subfolder`. The bucket already exist before attempting to upload.
* @param file The file object to be stored in the bucket.
* @param fileOptions HTTP headers. For example `cacheControl`
*/
async update(
path: string,
file: File,
fileOptions?: FileOptions
): Promise<{ data: { Key: string } | null; error: Error | null }> {
try {
if (!isBrowser()) throw new Error('No browser detected.')
const formData = new FormData()
formData.append('', file, file.name)
const options = { ...DEFAULT_FILE_OPTIONS, ...fileOptions }
formData.append('cacheControl', options.cacheControl)
const _path = this._getFinalPath(path)
const res = await fetch(`${this.url}/object/${_path}`, {
method: 'PUT',
body: formData,
headers: { ...this.headers },
})
if (res.ok) {
const data = await res.json()
return { data, error: null }
} else {
const error = await res.json()
return { data: null, error }
}
} catch (error) {
return { data: null, error }
}
}
/**
* Moves an existing file, optionally renaming it at the same time.
*
* @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 move(
fromPath: string,
toPath: string
): Promise<{ data: { message: string } | null; error: Error | null }> {
try {
const data = await post(
`${this.url}/object/move`,
{ 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 }> {
try {
const _path = this._getFinalPath(path)
let data = await post(
`${this.url}/object/sign/${_path}`,
{ expiresIn },
{ headers: this.headers }
)
const signedUrl = `${this.url}${data.signedUrl}`
data = { ...data, signedUrl }
return { data, 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.url}/object/${_path}`, {
headers: this.headers,
noResolveJson: true,
})
const data = await res.blob()
return { data, error: null }
} catch (error) {
return { data: null, error }
}
}
/**
* Deletes files within the same bucket
*
* @param paths An array of files to be deletes, 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.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`.
*/
async list(
path?: string,
options?: SearchOptions
): Promise<{ data: FileObject[] | null; error: Error | null }> {
try {
const body = { ...DEFAULT_SEARCH_OPTIONS, ...options, prefix: path || '' }
const data = await post(`${this.url}/object/list/${this.bucketId}`, body, {
headers: this.headers,
})
return { data, error: null }
} catch (error) {
return { data: null, error }
}
}
_getFinalPath(path: string) {
return `${this.bucketId}/${path}`
}
}