tsbase
Version:
Base class libraries for TypeScript
56 lines • 2.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpClient = void 0;
const HttpMethod_1 = require("./HttpMethod");
class HttpClient {
constructor(DefaultRequestHeaders, fetchRef) {
var _a;
if (DefaultRequestHeaders === void 0) { DefaultRequestHeaders = {}; }
if (fetchRef === void 0) { fetchRef = (_a = globalThis.fetch) === null || _a === void 0 ? void 0 : _a.bind(globalThis); }
this.DefaultRequestHeaders = DefaultRequestHeaders;
this.fetchRef = fetchRef;
}
async Request(uri, method, body, additionalHeaders) {
var _a, _b;
const request = new Request(uri, {
method,
body,
headers: { ...this.DefaultRequestHeaders, ...additionalHeaders }
});
const requestOrResponse = await ((_a = this.OnRequestReceived) === null || _a === void 0 ? void 0 : _a.call(this, request));
const response = requestOrResponse && requestOrResponse instanceof Response ?
requestOrResponse :
await this.fetchRef(request);
(_b = this.OnResponseResolved) === null || _b === void 0 ? void 0 : _b.call(this, response);
return response;
}
async Get(uri, additionalHeaders) {
return await this.getRestResponse(uri, HttpMethod_1.HttpMethod.Get, undefined, additionalHeaders);
}
async Patch(uri, body, additionalHeaders) {
return await this.getRestResponse(uri, HttpMethod_1.HttpMethod.Patch, body, additionalHeaders);
}
async Post(uri, body, additionalHeaders) {
return await this.getRestResponse(uri, HttpMethod_1.HttpMethod.Post, body, additionalHeaders);
}
async Put(uri, body, additionalHeaders) {
return await this.getRestResponse(uri, HttpMethod_1.HttpMethod.Put, body, additionalHeaders);
}
async Delete(uri, additionalHeaders) {
return await this.getRestResponse(uri, HttpMethod_1.HttpMethod.Delete, undefined, additionalHeaders);
}
async getRestResponse(uri, method, body, additionalHeaders) {
var _a;
const response = await this.Request(uri, method, body, additionalHeaders);
const isJson = (_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json');
return {
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: response.headers,
body: isJson ? await response.json() : await response.text()
};
}
}
exports.HttpClient = HttpClient;
//# sourceMappingURL=HttpClient.js.map