(
defaultOptions = {
baseURL: "",
}
)
| 189 | } |
| 190 | |
| 191 | function HTTP( |
| 192 | defaultOptions = { |
| 193 | baseURL: "", |
| 194 | } |
| 195 | ) { |
| 196 | const { isQX, isLoon, isSurge, isScriptable, isNode } = ENV(); |
| 197 | const methods = ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"]; |
| 198 | const URL_REGEX = |
| 199 | /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/; |
| 200 | |
| 201 | function send(method, options) { |
| 202 | options = |
| 203 | typeof options === "string" |
| 204 | ? { |
| 205 | url: options, |
| 206 | } |
| 207 | : options; |
| 208 | const baseURL = defaultOptions.baseURL; |
| 209 | if (baseURL && !URL_REGEX.test(options.url || "")) { |
| 210 | options.url = baseURL ? baseURL + options.url : options.url; |
| 211 | } |
| 212 | if (options.body && options.headers && !options.headers["Content-Type"]) { |
| 213 | options.headers["Content-Type"] = "application/x-www-form-urlencoded"; |
| 214 | } |
| 215 | options = { |
| 216 | ...defaultOptions, |
| 217 | ...options, |
| 218 | }; |
| 219 | const timeout = options.timeout; |
| 220 | const events = { |
| 221 | ...{ |
| 222 | onRequest: () => {}, |
| 223 | onResponse: (resp) => resp, |
| 224 | onTimeout: () => {}, |
| 225 | }, |
| 226 | ...options.events, |
| 227 | }; |
| 228 | |
| 229 | events.onRequest(method, options); |
| 230 | |
| 231 | let worker; |
| 232 | if (isQX) { |
| 233 | worker = $task.fetch({ |
| 234 | method, |
| 235 | ...options, |
| 236 | }); |
| 237 | } else if (isLoon || isSurge || isNode) { |
| 238 | worker = new Promise((resolve, reject) => { |
| 239 | const request = isNode ? require("request") : $httpClient; |
| 240 | request[method.toLowerCase()](options, (err, response, body) => { |
| 241 | if (err) reject(err); |
| 242 | else |
| 243 | resolve({ |
| 244 | statusCode: response.status || response.statusCode, |
| 245 | headers: response.headers, |
| 246 | body, |
| 247 | }); |
| 248 | }); |
no test coverage detected