MCPcopy Create free account
hub / github.com/Moli-X/Resources / HTTP

Function HTTP

Script/Hzh.js:191–297  ·  view source on GitHub ↗
(
  defaultOptions = {
    baseURL: "",
  }
)

Source from the content-addressed store, hash-verified

189}
190
191function 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 });

Callers 1

constructorMethod · 0.70

Calls 2

ENVFunction · 0.70
sendFunction · 0.70

Tested by

no test coverage detected