/
imgur.js
40 lines (38 loc) · 1.3 KB
/
imgur.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
/**
* @copyright 2023 Chris Zuber <admin@kernvalley.us>
*/
export const SUPPORTED_TYPES = ['image/jpeg', 'image/png'];
export async function upload(what, { clientId }) {
if (typeof clientId !== 'string' || clientId.length === 0) {
throw new Error('Missing clientId');
} else if (what instanceof File) {
if (! SUPPORTED_TYPES.includes(what.type)) {
throw new TypeError(`Unsupported file type: ${what.type}`);
}
const resp = await fetch('https://api.imgur.com/3/image', {
method: 'POST',
body: what,
headers: new Headers({
Authorization: `Client-ID ${clientId}`,
Accept: 'application/json',
})
});
if (resp.ok) {
return await resp.json();
} else {
const { data } = await resp.json()
.catch(() => ({ data: { error: `${resp.url} [${resp.status} ${resp.statusText}]` }}));
throw new Error(data.error);
}
} else if (what instanceof FileList && what.length !== 0) {
return await Promise.all(Array.from(what).map(f => upload(f, { clientId })));
} else if (Array.isArray(what)) {
return await Promise.all(what.map(item => upload(item, { clientId })));
} else if (what instanceof HTMLInputElement && what.type === 'file') {
if (what.multiple) {
return await upload(what.files, { clientId });
} else {
return await upload(what.files.item(0), { clientId });
}
}
}