-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
119 lines (119 loc) · 3.27 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const rq = require("request-promise-native");
const fs = require("fs");
const tmp = require("tmp");
const download = require("node-save-file");
const fsExtra = require("fs-extra");
const debug = require('debug')('upload-remote-file')
module.exports = class Upload {
constructor() {
this.cleanCallback = null;
}
request(options) {
options = Object.assign(
{
resolveWithFullResponse: true,
method: "POST"
},
options
);
var promises = [];
var p = Promise.resolve();
if (options.formData) {
var formData = options.formData;
for (var formKey in formData) {
if (formData.hasOwnProperty(formKey)) {
var formValue = formData[formKey];
if (formValue instanceof Array) {
for (var j = 0; j < formValue.length; j++) {
if (Promise.resolve(formValue[j]) == formValue[j]) {
promises.push({
type: "array",
key: formKey,
index: j,
promise: formValue[j]
});
}
}
} else {
if (Promise.resolve(formValue[j]) == formValue) {
promises.push({
type: "simple",
key: formKey,
promise: formValue
});
}
}
}
}
}
if (promises.length > 0) {
p = p.then(() => {
return Promise.all(promises.map(item => item.promise)).then(results => {
promises.forEach((item, index) => {
if (item.type === "array") {
options.formData[item.key][item.index] = results[index];
} else {
options.formData[item.key] = results[index];
}
});
return Promise.resolve();
});
});
}
p = p.then(() => {
debug('formData %o',options.formData)
return rq(options)
.then(data => {
// clean
if (this.cleanCallback) {
return this.cleanCallback().then(() => data);
} else {
return data;
}
})
.catch(e => {
// also clean
if (this.cleanCallback) {
return this.cleanCallback().then(() => {
return Promise.reject(e);
});
} else {
return Promise.reject(e);
}
});
});
return p;
}
getReadStream(remoteUrl,options) {
// getFiles
return new Promise((resolve, reject) => {
tmp.dir((err, dirPath, cleanupCallback) => {
if (err) {
return reject(err);
}
this.cleanCallback = function() {
return new Promise(resolve2 => {
cleanupCallback();
return resolve2();
});
};
download(remoteUrl, dirPath,options)
.then(result => {
this.cleanCallback = () => {
return fsExtra.remove(result.filepath).then(() => {
cleanupCallback();
return Promise.resolve();
});
};
return resolve(fs.createReadStream(result.filepath));
})
.then(data => {
resolve(data);
})
.catch(e => {
reject(e);
});
});
});
}
};