@chustasoft/cs-common
Version:
Common utilities for JavaScript projects equivalents to ChustaSoft CommonNET project
68 lines (67 loc) • 2.72 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpService = void 0;
const http_headers_builder_1 = require("../helpers/http-headers.builder");
class HttpService {
get(url, authData = null) {
return __awaiter(this, void 0, void 0, function* () {
return this.performUrlCall('GET', url, authData);
});
}
post(url, body, authData = null) {
return __awaiter(this, void 0, void 0, function* () {
return this.performBodyCall('POST', url, body, authData);
});
}
put(url, body, authData = null) {
return __awaiter(this, void 0, void 0, function* () {
return this.performBodyCall('PUT', url, body, authData);
});
}
delete(url, authData = null) {
return __awaiter(this, void 0, void 0, function* () {
return this.performUrlCall('DELETE', url, authData);
});
}
performUrlCall(action, url, authData = null) {
return fetch(url, {
method: action,
headers: new http_headers_builder_1.HttpHeadersBuilder().setAuthentication(authData).build()
})
.then(httpRespose => {
if (!httpRespose.ok) {
throw new Error(httpRespose.statusText);
}
return httpRespose.json();
})
.then(actionResponse => {
return actionResponse.data;
});
}
performBodyCall(action, url, body, authData = null) {
return fetch(url, {
method: action,
body: JSON.stringify(body),
headers: new http_headers_builder_1.HttpHeadersBuilder().setAuthentication(authData).build()
})
.then(httpRespose => {
if (!httpRespose.ok) {
throw new Error(httpRespose.statusText);
}
return httpRespose.json();
})
.then(actionResponse => {
return actionResponse.data;
});
}
}
exports.HttpService = HttpService;