forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.ts
More file actions
66 lines (62 loc) · 2.25 KB
/
fetch.ts
File metadata and controls
66 lines (62 loc) · 2.25 KB
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
/**
* Contains utility methods using 'fetch'.
*/
import {ApiError, ErrorCode} from '../core/api_error';
import {BFSCallback} from '../core/file_system';
export const fetchIsAvailable = (typeof(fetch) !== "undefined" && fetch !== null);
/**
* Asynchronously download a file as a buffer or a JSON object.
* Note that the third function signature with a non-specialized type is
* invalid, but TypeScript requires it when you specialize string arguments to
* constants.
* @hidden
*/
export function fetchFileAsync(p: string, type: 'buffer', cb: BFSCallback<Buffer>): void;
export function fetchFileAsync(p: string, type: 'json', cb: BFSCallback<any>): void;
export function fetchFileAsync(p: string, type: string, cb: BFSCallback<any>): void;
export function fetchFileAsync(p: string, type: string, cb: BFSCallback<any>): void {
let request;
try {
request = fetch(p);
} catch (e) {
// XXX: fetch will throw a TypeError if the URL has credentials in it
return cb(new ApiError(ErrorCode.EINVAL, e.message));
}
request
.then((res) => {
if (!res.ok) {
return cb(new ApiError(ErrorCode.EIO, `fetch error: response returned code ${res.status}`));
} else {
switch (type) {
case 'buffer':
res.arrayBuffer()
.then((buf) => cb(null, Buffer.from(buf)))
.catch((err) => cb(new ApiError(ErrorCode.EIO, err.message)));
break;
case 'json':
res.json()
.then((json) => cb(null, json))
.catch((err) => cb(new ApiError(ErrorCode.EIO, err.message)));
break;
default:
cb(new ApiError(ErrorCode.EINVAL, "Invalid download type: " + type));
}
}
})
.catch((err) => cb(new ApiError(ErrorCode.EIO, err.message)));
}
/**
* Asynchronously retrieves the size of the given file in bytes.
* @hidden
*/
export function fetchFileSizeAsync(p: string, cb: BFSCallback<number>): void {
fetch(p, { method: 'HEAD' })
.then((res) => {
if (!res.ok) {
return cb(new ApiError(ErrorCode.EIO, `fetch HEAD error: response returned code ${res.status}`));
} else {
return cb(null, parseInt(res.headers.get('Content-Length') || '-1', 10));
}
})
.catch((err) => cb(new ApiError(ErrorCode.EIO, err.message)));
}