|
3 | 3 | */
|
4 | 4 |
|
5 | 5 | const got = require('got');
|
| 6 | +const FormData = require('form-data'); |
6 | 7 |
|
7 | 8 | var initParams = function(uri, options, callback) {
|
8 | 9 |
|
@@ -141,20 +142,52 @@ module.exports = function(uri, options, callback) {
|
141 | 142 |
|
142 | 143 | };
|
143 | 144 |
|
| 145 | +/** |
| 146 | + * Uploads a file to the server |
| 147 | + * @param {string} url - url to upload file to |
| 148 | + * @param {object} fileData - file data object |
| 149 | + * @param {string} fileData.fileField - name of the field to upload file as |
| 150 | + * @param {string} fileData.fileStream - file stream to upload |
| 151 | + * @param {function} callback - callback function |
| 152 | + */ |
| 153 | +async function uploadFormFile(url, fileData, callback) { |
| 154 | + const { fileField, fileStream } = fileData; |
| 155 | + |
| 156 | + const form = new FormData(); |
| 157 | + form.append(fileField, fileStream); |
| 158 | + |
| 159 | + try { |
| 160 | + const response = await got.post(url, { |
| 161 | + body: form |
| 162 | + }); |
| 163 | + callback(null, response.body); |
| 164 | + } |
| 165 | + catch (error) { |
| 166 | + callback(error); |
| 167 | + } |
| 168 | +} |
| 169 | + |
144 | 170 | // Add a post method to the request object
|
145 | 171 | module.exports.post = function(uri, options, callback) {
|
146 | 172 | var params = initParams(uri, options, callback);
|
147 | 173 | if (params.options && (params.options.url || params.options.uri)) {
|
148 |
| - // Make the request using got |
149 |
| - got.post(params.options) |
150 |
| - .then(response => { |
151 |
| - // Call the callback with the response data |
152 |
| - params.callback(null, response, response.body); |
153 |
| - }) |
154 |
| - .catch(error => { |
155 |
| - // Call the callback with the error |
156 |
| - params.callback(error); |
157 |
| - }); |
| 174 | + if (params.options.form) { |
| 175 | + // If options include a form, use uploadFormFile |
| 176 | + const { url, form } = params.options; |
| 177 | + uploadFormFile(url || params.options.uri, form, params.callback); |
| 178 | + } |
| 179 | + else { |
| 180 | + // Make the request using got |
| 181 | + got.post(params.options) |
| 182 | + .then(response => { |
| 183 | + // Call the callback with the response data |
| 184 | + params.callback(null, response, response.body); |
| 185 | + }) |
| 186 | + .catch(error => { |
| 187 | + // Call the callback with the error |
| 188 | + params.callback(error); |
| 189 | + }); |
| 190 | + } |
158 | 191 | }
|
159 | 192 | else {
|
160 | 193 | // Make the request using got
|
|
0 commit comments