@hubs101/js-api-skd-client
Version:
Package for easy access to Event App API
586 lines (585 loc) • 24.6 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.putRequestDirect = exports.postWithAttachments = exports.patchRequestWe = exports.postRequestJSON = exports.postFileRequestWE = exports.deleteRequestWE = exports.postRequestWE = exports.postRequestWithRetry = exports.postFilesAndDataRequest = exports.validateBaseUrl = exports.validateConfig = exports.getFormRequest = exports.getRequest = exports.patchRequestDirect = exports.patchRequest = exports.putRequest = exports.postFileRequest = exports.deleteRequest = exports.getRequestSimple = exports.postRequestSimple = exports.postRequest = exports.trimUndefined = exports.error400 = void 0;
exports.error400 = '"status":400';
const trimUndefined = (obj) => Object.keys(obj).reduce((result, key) => obj[key] === undefined ? result : ((result[key] = obj[key]), result), {});
exports.trimUndefined = trimUndefined;
const postRequest = (url, body, token, headers) => __awaiter(void 0, void 0, void 0, function* () {
let form;
if (body) {
if (headers &&
headers["Content-Type"] === "application/x-www-form-urlencoded") {
form = new URLSearchParams();
}
else {
form = new FormData();
}
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => Array.isArray(body[key])
? form.append(key, JSON.stringify(body[key]))
: form.append(key, body[key]));
}
const response = yield fetch(url, {
method: "POST",
headers: token
? Object.assign({ accept: "application/json", Authorization: `Bearer ${token}` }, headers) : Object.assign({}, headers),
body: form,
});
let data = null;
try {
data = yield response.json();
}
catch (e) {
console.log("Error in postRequest", e);
}
if (String(data === null || data === void 0 ? void 0 : data.status).startsWith("4")) {
if (data === null || data === void 0 ? void 0 : data.invalid_fields) {
throw data.invalid_fields;
}
if (data === null || data === void 0 ? void 0 : data.message) {
throw data.message;
}
}
if ((data === null || data === void 0 ? void 0 : data.result) && typeof (data === null || data === void 0 ? void 0 : data.result) !== "string") {
return data === null || data === void 0 ? void 0 : data.result;
}
if (data === null) {
return response;
}
return data;
});
exports.postRequest = postRequest;
const postRequestSimple = (url, body, headers) => __awaiter(void 0, void 0, void 0, function* () {
// console.log('postBody:' + JSON.stringify(body));
let form;
if (body) {
form = new FormData();
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => Array.isArray(body[key])
? form.append(key, JSON.stringify(body[key]))
: form.append(key, body[key]));
}
const response = yield fetch(url, {
method: "POST",
headers: Object.assign({ accept: "application/json" }, headers),
body: form,
});
// console.log('postRequestSimple:' + JSON.stringify(response));
const data = yield response.json();
if (String(data.status).startsWith("4")) {
if (data === null || data === void 0 ? void 0 : data.invalid_fields) {
throw data.invalid_fields;
}
if (data === null || data === void 0 ? void 0 : data.message) {
throw data.message;
}
}
if ((data === null || data === void 0 ? void 0 : data.result) && typeof (data === null || data === void 0 ? void 0 : data.result) !== "string") {
return data === null || data === void 0 ? void 0 : data.result;
}
return data;
});
exports.postRequestSimple = postRequestSimple;
const getRequestSimple = (url, token, headers) => __awaiter(void 0, void 0, void 0, function* () {
const response = yield fetch(url, {
method: "GET",
headers: token
? Object.assign({ Authorization: `Bearer ${token}` }, headers) : Object.assign({}, headers),
});
return response.text();
});
exports.getRequestSimple = getRequestSimple;
const deleteRequest = (url, body, token, headers) => __awaiter(void 0, void 0, void 0, function* () {
let form;
if (body) {
form = new FormData();
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => Array.isArray(body[key])
? form.append(key, JSON.stringify(body[key]))
: form.append(key, body[key]));
}
const requestOptions = {
method: "DELETE",
headers: Object.assign({ Authorization: `Bearer ${token}` }, headers),
};
// Only add body if form has content
if (form) {
requestOptions.body = form;
}
const response = yield fetch(url, requestOptions);
const data = yield response.json();
if (String(data.status).startsWith("4")) {
if (data === null || data === void 0 ? void 0 : data.message) {
throw new Error(data.message);
}
if (data === null || data === void 0 ? void 0 : data.invalid_fields) {
throw new Error(JSON.stringify(data.invalid_fields));
}
}
if (data === null || data === void 0 ? void 0 : data.result) {
return data === null || data === void 0 ? void 0 : data.result;
}
return data;
});
exports.deleteRequest = deleteRequest;
const postFileRequest = (url, file, param, token) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b;
const formdata = new FormData();
if ((file === null || file === void 0 ? void 0 : file.length) > 0 || ((_a = file === null || file === void 0 ? void 0 : file.path) === null || _a === void 0 ? void 0 : _a.length) > 0) {
// to handle both android and ios
formdata.append(param, {
name: file.path
? file.filename ||
`${new Date().getTime()}.${(_b = file === null || file === void 0 ? void 0 : file.path) === null || _b === void 0 ? void 0 : _b.split(".").pop()}`
: undefined,
type: file.mime,
uri: file === null || file === void 0 ? void 0 : file.path,
});
}
else {
formdata.append(param, "");
}
formdata.append("_method", "put");
const response = yield fetch(url, {
method: "POST",
headers: {
accept: "application/json",
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${token}`,
},
body: formdata,
});
const data = yield response.json();
if (data.status === 401) {
throw new Error(data.message);
}
if (!(data === null || data === void 0 ? void 0 : data.result)) {
throw new Error("update failed");
}
if (data.message) {
throw new Error(data.message);
}
return data === null || data === void 0 ? void 0 : data.result;
});
exports.postFileRequest = postFileRequest;
const putRequest = (url_1, token_1, body_1, ...args_1) => __awaiter(void 0, [url_1, token_1, body_1, ...args_1], void 0, function* (url, token, body, withoutStatus = true) {
let form;
if (body) {
form = new FormData();
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => Array.isArray(body[key])
? form.append(key, JSON.stringify(body[key]))
: form.append(key, body[key]));
form.append("_method", "put");
}
const response = yield fetch(url, {
method: "POST", // Don't change it according changes happened in backend https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
headers: {
accept: "application/json",
Authorization: `Bearer ${token}`,
},
body: form,
});
const data = yield response.json();
if (String(data.status).startsWith("4")) {
if (data === null || data === void 0 ? void 0 : data.message) {
throw data.message;
}
if (data === null || data === void 0 ? void 0 : data.invalid_fields) {
throw new Error(`invalid_fields: ${data.invalid_fields}`);
}
}
if ((data === null || data === void 0 ? void 0 : data.result) && typeof (data === null || data === void 0 ? void 0 : data.result) !== "string" && withoutStatus) {
return data === null || data === void 0 ? void 0 : data.result;
}
return data;
});
exports.putRequest = putRequest;
const patchRequest = (url, token, body) => __awaiter(void 0, void 0, void 0, function* () {
let form;
if (body) {
form = new FormData();
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => form.append(key, JSON.stringify(body[key])));
form.append("_method", "patch");
}
const response = yield fetch(url, {
method: "POST", // Don't change it according changes happened in backend https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
headers: {
accept: "application/json",
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${token}`,
},
body: form,
});
const data = yield response.json();
if (String(data.status).startsWith("4")) {
if (data === null || data === void 0 ? void 0 : data.message) {
throw data.message;
}
if (data === null || data === void 0 ? void 0 : data.invalid_fields) {
throw new Error(`invalid_fields: ${data.invalid_fields}`);
}
}
return data;
});
exports.patchRequest = patchRequest;
const patchRequestDirect = (url, token, body) => __awaiter(void 0, void 0, void 0, function* () {
let form;
if (body) {
form = new FormData();
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => form.append(key, JSON.stringify(body[key])));
}
const response = yield fetch(url, {
method: "PATCH",
headers: {
accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: form,
});
const data = yield response.json();
if (String(data.status).startsWith("4")) {
if (data === null || data === void 0 ? void 0 : data.message) {
throw data.message;
}
if (data === null || data === void 0 ? void 0 : data.invalid_fields) {
throw new Error(`invalid_fields: ${data.invalid_fields}`);
}
}
return data;
});
exports.patchRequestDirect = patchRequestDirect;
const getRequest = (url, token, headers) => __awaiter(void 0, void 0, void 0, function* () {
const response = yield fetch(url, {
method: "GET",
headers: token
? Object.assign({ accept: "application/json", Authorization: `Bearer ${token}` }, headers) : Object.assign({ accept: "application/json" }, headers),
});
// console.log(`url:${url}`); // USE for performance monitoring
const data = yield response.json();
if (String(data === null || data === void 0 ? void 0 : data.status).startsWith("4")) {
console.log(`Error:${data.status} for url:${url}`);
throw new Error(data.message);
}
if ((data === null || data === void 0 ? void 0 : data.error) && (data === null || data === void 0 ? void 0 : data.message)) {
console.log(`Error:${data.status} for url:${url}`);
throw new Error(data.message);
}
if ((data === null || data === void 0 ? void 0 : data.result) && typeof (data === null || data === void 0 ? void 0 : data.result) !== "string") {
return data.result;
}
return data;
});
exports.getRequest = getRequest;
const getFormRequest = (url, token, body, headers) => __awaiter(void 0, void 0, void 0, function* () {
const form = new FormData();
Object.keys((0, exports.trimUndefined)(body)).forEach((item) => {
form.append(item, body[item]);
});
const response = yield fetch(url, {
method: "GET",
headers: Object.assign({ accept: "application/json", Authorization: `Bearer ${token}` }, headers),
});
const data = yield response.json();
if (data.status === 401) {
console.log(`Error:${data.message} for url:${url}`);
throw new Error(data.message);
}
return data.result;
});
exports.getFormRequest = getFormRequest;
const validateConfig = (config) => {
if (!config.baseUrl) {
throw Error("Base url not set");
}
if (!config.token) {
throw Error("Authentication token missing");
}
};
exports.validateConfig = validateConfig;
const validateBaseUrl = (config) => {
if (!config.baseUrl) {
throw Error("Base url not set");
}
};
exports.validateBaseUrl = validateBaseUrl;
const postFilesAndDataRequest = (url, payload, files, token, method) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b;
const getFormData = (object) => Object.keys(object).reduce((form, key) => {
form.append(key, object[key]);
return form;
}, new FormData());
const headers = new Headers();
const formData = getFormData((0, exports.trimUndefined)(payload));
files === null || files === void 0 ? void 0 : files.forEach((file) => {
if (file.value && typeof file.value === "string") {
return;
}
if (!file.value) {
formData.append(file.name, "");
}
else {
formData.append(file.name, file.value, file.name);
}
});
if (method)
formData.append("_method", method);
headers.append("Authorization", `Bearer ${token}`);
const requestOptions = {
method: "POST",
headers,
body: formData,
redirect: "follow",
};
const response = yield fetch(url, requestOptions);
if (response.status === 500) {
throw new Error(response.statusText);
}
const data = yield response.json();
if (data.status === 401) {
throw new Error(data.message);
}
if ((data === null || data === void 0 ? void 0 : data.status) === 403) {
throw new Error("Sorry you don't have enough access. Please make sure you have the correct right access.");
}
if (data.status === 400 && data.invalid_fields) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string
throw new Error((_a = Object.values(data === null || data === void 0 ? void 0 : data.invalid_fields)) === null || _a === void 0 ? void 0 : _a.join(", "));
}
const isSuccess = (data === null || data === void 0 ? void 0 : data.status) >= 200 && (data === null || data === void 0 ? void 0 : data.status) <= 299;
if (!isSuccess && !(data === null || data === void 0 ? void 0 : data.result)) {
throw new Error("Update failed");
}
if (!isSuccess && data.message) {
throw new Error(data.message);
}
return (_b = data === null || data === void 0 ? void 0 : data.result) !== null && _b !== void 0 ? _b : data === null || data === void 0 ? void 0 : data.message;
});
exports.postFilesAndDataRequest = postFilesAndDataRequest;
const postRequestWithRetry = (url, body, token, headers, retries) => __awaiter(void 0, void 0, void 0, function* () {
let retryCount = 0;
let data = null;
let form;
if (body) {
form = new FormData();
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => Array.isArray(body[key])
? form.append(key, JSON.stringify(body[key]))
: form.append(key, body[key]));
}
while (retryCount < retries) {
retryCount++;
const response = yield fetch(url, {
method: "POST",
headers: token
? Object.assign({ Authorization: `Bearer ${token}` }, headers) : Object.assign({}, headers),
body: form,
});
data = yield response.text();
if ((data === null || data === void 0 ? void 0 : data.length) > 300 || (data === null || data === void 0 ? void 0 : data.indexOf(exports.error400)) > -1)
break;
else
yield new Promise((resolve) => setTimeout(resolve, 3000));
}
return data;
});
exports.postRequestWithRetry = postRequestWithRetry;
const postRequestWE = (url, body, token, headers) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
let form;
if (body) {
if (headers &&
headers["Content-Type"] === "application/x-www-form-urlencoded") {
form = new URLSearchParams();
}
else {
form = new FormData();
}
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => Array.isArray(body[key])
? form.append(key, JSON.stringify(body[key]))
: form.append(key, body[key]));
}
const response = yield fetch(url, {
method: "POST",
headers: token
? Object.assign({ Authorization: `Bearer ${token}` }, headers) : Object.assign({}, headers),
body: form,
});
if (String(response.status).startsWith("5")) {
throw new Error(response.statusText);
}
const data = yield response.json();
if ((data === null || data === void 0 ? void 0 : data.message_code) === 40900000) {
throw new Error("errors.api-40900000");
}
if (data.status === 400 && data.invalid_fields) {
throw new Error((_a = Object.values(data === null || data === void 0 ? void 0 : data.invalid_fields)) === null || _a === void 0 ? void 0 : _a.toString());
}
if (String(data.status).startsWith("4")) {
throw new Error(data.message);
}
return data;
});
exports.postRequestWE = postRequestWE;
const deleteRequestWE = (url, token) => __awaiter(void 0, void 0, void 0, function* () {
return yield (0, exports.postFilesAndDataRequest)(url, {}, [], token, "delete");
});
exports.deleteRequestWE = deleteRequestWE;
const postFileRequestWE = (url, file, param, token) => __awaiter(void 0, void 0, void 0, function* () {
const formdata = new FormData();
const headers = new Headers();
if (!file) {
headers.append("accept", "application/json");
formdata.append(param, "");
}
else {
formdata.append(param, file, file.name);
}
formdata.append("_method", "put");
headers.append("Authorization", `Bearer ${token}`);
const requestOptions = {
method: "POST",
headers,
body: formdata,
redirect: "follow",
};
const response = yield fetch(url, requestOptions);
const data = yield response.json();
if (data.status === 401) {
throw new Error(data.message);
}
if (!(data === null || data === void 0 ? void 0 : data.result)) {
throw new Error("update failed");
}
if (data.message) {
throw new Error(data.message);
}
return data === null || data === void 0 ? void 0 : data.result;
});
exports.postFileRequestWE = postFileRequestWE;
const postRequestJSON = (url, body, token, headers) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
let form;
if (body) {
if ((headers &&
headers["Content-Type"] === "application/x-www-form-urlencoded") ||
headers["Content-Type"] === "application/json") {
form = new URLSearchParams();
}
else {
form = new FormData();
}
Object.keys((0, exports.trimUndefined)(body)).forEach((key) => Array.isArray(body[key])
? form.append(key, JSON.stringify(body[key]))
: form.append(key, body[key]));
}
const response = yield fetch(url, {
method: "POST",
headers: token
? Object.assign({ Authorization: `Bearer ${token}` }, headers) : Object.assign({}, headers),
body: headers["Content-Type"] === "application/json"
? JSON.stringify(body)
: form,
});
if (String(response.status).startsWith("5")) {
throw new Error(response.statusText);
}
const data = yield response.json();
if ((data === null || data === void 0 ? void 0 : data.message_code) === 40900000) {
throw new Error("errors.api-40900000");
}
if (data.status === 400 && data.invalid_fields) {
throw new Error((_a = Object.values(data === null || data === void 0 ? void 0 : data.invalid_fields)) === null || _a === void 0 ? void 0 : _a.toString());
}
if (String(data.status).startsWith("4")) {
throw new Error(data.message);
}
return data;
});
exports.postRequestJSON = postRequestJSON;
const patchRequestWe = (url, body, token) => __awaiter(void 0, void 0, void 0, function* () { return yield (0, exports.postFilesAndDataRequest)(url, body, [], token, "patch"); });
exports.patchRequestWe = patchRequestWe;
const postWithAttachments = (url, formData, token, headers) => __awaiter(void 0, void 0, void 0, function* () {
try {
// Validate required parameters
if (!url) {
throw new Error("URL is required");
}
if (!token) {
throw new Error("Authentication token is required");
}
if (!formData) {
throw new Error("Form data is required");
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout
try {
const response = yield fetch(url, {
method: "POST",
headers: Object.assign({ Accept: "application/json", Authorization: `Bearer ${token}` }, headers),
body: formData,
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = yield response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = yield response.json();
// Handle different response formats
if (data === null || data === void 0 ? void 0 : data.result) {
return data.result;
}
if (data === null || data === void 0 ? void 0 : data.data) {
return data.data;
}
return data;
}
catch (fetchError) {
clearTimeout(timeoutId);
if (fetchError.name === "AbortError") {
throw new Error("Request timeout - network may be slow or unavailable");
}
throw fetchError;
}
}
catch (error) {
console.error("postWithAttachments error:", error.message);
throw error;
}
});
exports.postWithAttachments = postWithAttachments;
const putRequestDirect = (url, token, body) => __awaiter(void 0, void 0, void 0, function* () {
const response = yield fetch(url, {
method: "PUT",
headers: {
accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
});
const data = yield response.json();
if (String(data.status).startsWith("4")) {
if (data === null || data === void 0 ? void 0 : data.message) {
throw data.message;
}
if (data === null || data === void 0 ? void 0 : data.invalid_fields) {
throw new Error(JSON.stringify({ invalid_fields: data.invalid_fields }));
}
}
if ((data === null || data === void 0 ? void 0 : data.result) && typeof (data === null || data === void 0 ? void 0 : data.result) !== "string") {
return data === null || data === void 0 ? void 0 : data.result;
}
if (data) {
console.log(`Error:${data.error} for message:${data === null || data === void 0 ? void 0 : data.message} url:${url}`);
throw new Error(data.message);
}
return data;
});
exports.putRequestDirect = putRequestDirect;