-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-pool.js
87 lines (66 loc) · 1.72 KB
/
file-pool.js
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
import { define, Component } from '@xinix/xin';
const globalPools = [];
export class FilePool extends Component {
static get default () {
return globalPools[0];
}
get props () {
return Object.assign({}, super.props, {
name: {
type: String,
},
baseUrl: {
type: String,
value: window.location.origin,
observer: 'baseUrlChanged(baseUrl)',
},
headers: {
type: Object,
},
});
}
baseUrlChanged (baseUrl) {
this._baseUrl = (new window.URL(baseUrl, window.location.origin).href).replace(/\/+$/, '');
}
getUrl (url = '') {
if (url instanceof window.URL) {
return url;
}
return url.startsWith('/') ? ((this._baseUrl || '') + url) : new window.URL(url, this._baseUrl).href;
}
async upload (files = [], { bucket = '/' } = {}) {
let data = new window.FormData();
files.forEach(file => {
data.append('file', file);
});
let resp = await this.fetch(`/upload?bucket=${bucket}`, {
method: 'POST',
body: data,
});
if (resp.status !== 200) {
throw new Error('Fail uploading');
}
return resp.json();
}
fetch (url, options = {}) {
const headers = Object.assign({}, this.headers, options.headers);
delete headers['Content-Type'];
options = Object.assign(options, { headers });
return window.fetch(this.getUrl(url), options);
}
attached () {
super.attached();
if (!this.name) {
this.name = `filepool-${this.__id}`;
}
globalPools.push(this);
}
detached () {
super.detached();
const index = globalPools.indexOf(this);
if (index !== -1) {
globalPools.splice(index, 1);
}
}
}
define('file-pool', FilePool);