/
collection.ts
67 lines (53 loc) · 1.58 KB
/
collection.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
import { Collection } from '../types'
import { BeeArgumentError } from './error'
import { fileArrayBuffer } from './file'
import { isUint8Array } from './type'
export function isCollection(data: unknown): data is Collection<Uint8Array> {
if (!Array.isArray(data)) {
return false
}
return data.every(entry => typeof entry === 'object' && entry.data && entry.path && isUint8Array(entry.data))
}
export function assertCollection(data: unknown): asserts data is Collection<Uint8Array> {
if (!isCollection(data)) {
throw new BeeArgumentError('invalid collection', data)
}
}
function makeFilePath(file: File) {
if (file.webkitRelativePath && file.webkitRelativePath !== '') {
return file.webkitRelativePath.replace(/.*?\//i, '')
}
if (file.name) {
return file.name
}
throw new TypeError('file is not valid File object')
}
export async function makeCollectionFromFileList(fileList: FileList | File[]): Promise<Collection<Uint8Array>> {
const collection: Collection<Uint8Array> = []
for (let i = 0; i < fileList.length; i++) {
const file = fileList[i]
if (file) {
collection.push({
path: makeFilePath(file),
data: new Uint8Array(await fileArrayBuffer(file)),
})
}
}
return collection
}
/**
* Calculate cumulative size of files
*
* @param fileList list of files to check
* @returns size in bytes
*/
export function getCollectionSize(fileList: FileList | File[]): number {
let sum = 0
for (let i = 0; i < fileList.length; i++) {
const file = fileList[i]
if (file) {
sum += file.size
}
}
return sum
}