@tf2pickup-org/serveme-tf-client
Version:
A serveme.tf API client
60 lines • 1.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpClient = void 0;
const http_client_error_1 = require("./errors/http-client.error");
const http_method_1 = require("./http-method");
const is_absolute_url_1 = require("./is-absolute-url");
class HttpClient {
constructor(options) {
this.baseUrl = options.baseUrl;
this.params = options.params;
}
async request(method, path, body) {
const url = this.createUrl(path);
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
},
...(body ? { body: JSON.stringify(body) } : {}),
});
if (response.ok) {
return (await response.json());
}
else {
throw new http_client_error_1.HttpClientError(url, response.status, response.statusText, await response.text());
}
}
async get(path) {
return await this.request(http_method_1.HttpMethod.GET, path);
}
async post(path, body) {
return await this.request(http_method_1.HttpMethod.POST, path, body);
}
async put(path, body) {
return await this.request(http_method_1.HttpMethod.PUT, path, body);
}
async delete(path) {
return await this.request(http_method_1.HttpMethod.DELETE, path, {});
}
createUrl(path) {
let url;
if ((0, is_absolute_url_1.isAbsoluteUrl)(path)) {
url = new URL(path);
}
else {
url = new URL([this.baseUrl, path]
.filter(Boolean)
.join('/')
.replace(/([^:]\/)\/+/g, '$1'));
}
if (this.params) {
for (const [key, value] of Object.entries(this.params)) {
url.searchParams.append(key, value);
}
}
return url;
}
}
exports.HttpClient = HttpClient;
//# sourceMappingURL=http-client.js.map