-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetcall.js
More file actions
75 lines (68 loc) · 1.82 KB
/
Copy pathnetcall.js
File metadata and controls
75 lines (68 loc) · 1.82 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
67
68
69
70
71
72
73
74
75
const fs = require('fs');
const _ = require('lodash');
const {JSDOM} = require('jsdom');
const {Readable} = require('stream');
const {finished} = require('stream/promises');
const {wait} = require('./concurrent.js');
const E = module.exports = netCall;
const qsParse = (qs={})=>{
let result = Object.entries(qs)
.map(([k, v])=>`${k}=${encodeURIComponent(v)}`)
.join('&');
if (result.length)
result = '?'+result;
return result;
};
async function netCall(opt={}) {
if (_.isString(opt))
opt = {url: opt};
let {
url,
method = 'GET',
headers = {},
qs,
payload,
formData,
file,
} = opt;
url += qsParse(qs);
let body;
if (payload) {
body = JSON.stringify(payload);
} else if (formData) {
body = formData;
} else if (file) {
const stats = fs.statSync(file);
headers['Content-length'] = stats.size;
body = fs.createReadStream(file);
}
return await fetch(url, {headers, method, body});
}
E.text = async (opt={})=>{
const response = await netCall(opt);
return await response.text();
};
E.json = async (opt={})=>{
const response = await netCall(opt);
return await response.json();
};
E.dom = async (opt={})=>{
const response = await E.text(opt);
const {document} = new JSDOM(response).window;
return document;
};
E.stream = (opt={})=>{
const w = wait();
netCall(opt).then(w.resolve).catch(w.reject);
const get = async ()=>{
let resp = await w.promise;
return resp.body ? Readable.fromWeb(resp.body) : null;
};
const pipe = async to=>{
await finished((await get())?.pipe(to));
};
const toFile = async path=>{
await pipe(fs.createWriteStream(path, {flags: 'wx'}));
};
return {get, pipe, toFile};
};