util-http
Version:
88 lines (87 loc) • 2.95 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const undici_1 = require("undici");
const Constants_1 = require("../Constants");
const HttpClient_1 = __importDefault(require("./HttpClient"));
class UndiciClient {
static _instance;
contentHandlers = {
json: async (body) => body.json(),
urlencoded: async (body) => body.formData(),
formData: async (body) => body.formData(),
text: async (body) => body.text(),
buffer: async (body) => body.arrayBuffer()
};
static getInstance() {
UndiciClient._instance ||= new UndiciClient();
return UndiciClient._instance;
}
async custom(config) {
const url = `${config.url}`;
if (config.timeout === 0)
config.timeout = 15000;
const newConfig = {
...config,
data: undefined,
url: undefined,
body: typeof config.data === "object" ? JSON.stringify(config.data) : config.data
};
Reflect.deleteProperty(newConfig, "data");
Reflect.deleteProperty(newConfig, "url");
const response = await (0, undici_1.request)(url, newConfig).catch((error) => {
throw HttpClient_1.default.handleErrors(error, 500, "undici");
});
const contentTypeRaw = (response.headers["Content-Type"] || response.headers["content-type"]);
if (!contentTypeRaw) {
throw new Error("No Content-Type header");
}
const contentType = contentTypeRaw.split(";")[0];
if (!contentType) {
throw new Error("No Content-Type header");
}
const handlerKey = Constants_1.contentTypes[contentType];
if (!handlerKey) {
throw new Error(`Unsupported Content-Type: ${contentType}`);
}
if (response.statusCode < 200 || response.statusCode > 299) {
const errorData = (await response.body.json());
throw HttpClient_1.default.handleErrors(errorData, response.statusCode, "undici");
}
const handler = this.contentHandlers[handlerKey];
return (await handler(response.body));
}
async get(options) {
return this.custom({
...options,
method: "GET"
});
}
async post(options) {
return this.custom({
...options,
method: "POST"
});
}
async patch(options) {
return this.custom({
...options,
method: "PATCH"
});
}
async put(options) {
return this.custom({
...options,
method: "PUT"
});
}
async delete(options) {
return this.custom({
...options,
method: "DELETE"
});
}
}
exports.default = UndiciClient;