robert
Version:
A generic shitty http client in nod.js
126 lines (125 loc) • 4.05 kB
JavaScript
import { parseSize, parseTime } from "robert-util";
import request from "./request";
export default function (options) {
options ??= {};
if (typeof options === "string" || options instanceof URL)
options = { base: options };
let base = "";
if (options.base)
base = options.base.toString();
const opts = {
full: options.full ?? false,
port: options.port ?? null,
size: parseSize(options.size ?? "100mb"),
query: options.query ?? new URLSearchParams(),
format: options.format ?? "stream",
headers: options.headers ? { ...options.headers } : {},
timeout: parseTime(options.timeout ?? "1m"),
redirects: 10,
};
function init(method) {
return function (url = "") {
url = new URL(base + url);
const clone = {
...opts,
headers: { ...opts.headers },
query: new URLSearchParams(opts.query),
port: opts.port ?? parseInt(url.port),
};
const entries = url.searchParams.entries();
for (const [key, value] of entries)
clone.query.append(key, value);
url.search = "";
return request(method, url, clone);
};
}
return Object.assign(init("GET"), {
get: init("GET"),
put: init("PUT"),
head: init("HEAD"),
post: init("POST"),
patch: init("PATCH"),
delete: init("DELETE"),
options: init("OPTIONS"),
full() {
opts.full = !opts.full;
return this;
},
format(format) {
opts.format = format;
return this;
},
base(url) {
base = url.toString();
return this;
},
port(port) {
opts.port = port;
return this;
},
redirects(redirects) {
opts.redirects = redirects;
return this;
},
size(size) {
opts.size = parseSize(size);
return this;
},
timeout(time) {
opts.timeout = parseTime(time);
return this;
},
query(key, value) {
opts.query.append(key.toString(), value.toString());
return this;
},
setQuery(query) {
// alright so i want to find a formal fix for this
// types only allow strings in paramaters: string[][] | Record<string, string> | string | URLSearchParams
// though it accepts and i want to be able to pass through Record<Key, Value> | Value[][] | URLSearchParams | string
// @ts-ignore
opts.query = new URLSearchParams(query);
return this;
},
addQuery(query) {
// @ts-ignore same thing again
const entries = new URLSearchParams(query).entries();
for (const [key, value] of entries)
opts.query.append(key, value);
return this;
},
delQuery(key) {
// @ts-ignore pain
opts.query.delete(key);
return this;
},
header(key, value) {
opts.headers[key] = value;
return this;
},
setHeaders(headers) {
opts.headers = headers;
return this;
},
addHeaders(headers) {
Object.assign(opts.headers, headers);
return this;
},
delHeader(key) {
delete opts.headers[key];
return this;
},
auth(value) {
this.header("authorization", value);
return this;
},
agent(value) {
this.header("user-agent", value);
return this;
},
contentType(value) {
this.header("content-type", value);
return this;
},
});
}