@web-atoms/core
Version:
375 lines (374 loc) • 12.5 kB
JavaScript
System.register(["tslib", "../App"], function (_export, _context) {
"use strict";
var __addDisposableResource, __awaiter, __disposeResources, App, FetchBuilder, JsonError;
_export("default", void 0);
return {
setters: [function (_tslib) {
__addDisposableResource = _tslib.__addDisposableResource;
__awaiter = _tslib.__awaiter;
__disposeResources = _tslib.__disposeResources;
}, function (_App) {
App = _App.App;
}],
execute: function () {
_export("default", FetchBuilder = class FetchBuilder {
static buildUrl(strings, ...p) {
let r = "";
for (let index = 0; index < strings.length; index++) {
const element = strings[index];
r += element;
if (index < p.length) {
r += encodeURIComponent(p[index]);
}
}
return r;
}
static get(url) {
return this.method(url, "GET");
}
static put(url) {
return this.method(url, "PUT");
}
static post(url) {
return this.method(url, "POST");
}
static delete(url) {
return this.method(url, "DELETE");
}
static url(url) {
return this.method(url, "GET");
}
static header(name, value) {
return new FetchBuilder({
headers: {
url: "",
method: "POST",
[name]: value
}
});
}
static method(url, method) {
return new FetchBuilder({
url,
method
});
}
constructor(request) {
this.request = request;
}
log(logger) {
return this.append({
log: logger
});
}
logWhenFailed(logger) {
return this.append({
logError: logger
});
}
get(url) {
return this.method(url, "GET");
}
put(url) {
return this.method(url, "PUT");
}
post(url) {
return this.method(url, "POST");
}
delete(url) {
return this.method(url, "DELETE");
}
method(url, method) {
return this.append({
url,
method
});
}
signal(signal) {
if (!signal) {
return this;
}
return this.append({
signal
});
}
cancelToken(ct) {
if (!ct) {
return this;
}
const ac = new AbortController();
const signal = ac.signal;
ct.registerForCancel(() => ac.abort());
return this.signal(signal);
}
form(name, value, fileName) {
var _a;
if (value === void 0) {
return this;
}
const body = (_a = this.request.body) !== null && _a !== void 0 ? _a : new FormData();
if (fileName) {
if (typeof value === "string") {
throw new Error("value must be a blob with content type set correctly.");
}
body.append(name, value, fileName);
} else {
body.append(name, value);
}
return this.append({
body
});
}
jsonBody(body, encode = true) {
var _a;
if (encode) {
body = JSON.stringify(body);
}
const headers = (_a = this.request.headers) !== null && _a !== void 0 ? _a : {};
headers["content-type"] = "application/json";
return this.append({
body,
headers
});
}
header(name, value) {
var _a;
const headers = (_a = this.request.headers) !== null && _a !== void 0 ? _a : {};
headers[name] = value;
return this.append({
headers
});
}
path(name, value, encode = true) {
let url = this.request.url;
if (encode) {
value = encodeURIComponent(value);
}
url = url.replace(name, value);
return this.append({
url
});
}
query(name, value, encode = true) {
if (value === void 0) {
return this;
}
let url = this.request.url;
if (encode) {
value = encodeURIComponent(value);
}
name = encodeURIComponent(name);
if (url.indexOf("?") === -1) {
url += `?${name}=${value}`;
} else {
url += `&${name}=${value}`;
}
return this.append({
url
});
}
queries(obj, encode = true, encodeObjectAsJson = true) {
let url = this.request.url;
let prefix = url.indexOf("?") === -1 ? "?" : "&";
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
let value = obj[key];
if (value === void 0) {
continue;
}
if (encodeObjectAsJson) {
if (typeof value === "object" && value !== null) {
value = JSON.stringify(value);
}
encode = true;
}
if (encode) {
value = encodeURIComponent(value);
}
const name = encodeURIComponent(key);
url += `${prefix}${name}=${value}`;
prefix = "&";
}
}
return this.append({
url
});
}
asText() {
return __awaiter(this, arguments, void 0, function* (ensureSuccess = true) {
const {
result
} = yield this.asTextResponse(ensureSuccess);
return result;
});
}
asBlob() {
return __awaiter(this, arguments, void 0, function* (ensureSuccess = true) {
const {
result
} = yield this.asBlobResponse(ensureSuccess);
return result;
});
}
asJson() {
return __awaiter(this, arguments, void 0, function* (ensureSuccess = true) {
const {
result
} = yield this.asJsonResponse(ensureSuccess);
return result;
});
}
jsonPostProcessor(jsonPostProcessor) {
return this.append({
jsonPostProcessor
});
}
asJsonResponse() {
return __awaiter(this, arguments, void 0, function* (ensureSuccess = true) {
return this.execute(ensureSuccess, (x, jsonPostProcessor) => __awaiter(this, void 0, void 0, function* () {
if (!/json/i.test(x.headers.get("content-type"))) {
throw new Error(`Failed to parse json from ${this.request.url}\n${yield x.text()}`);
}
if (jsonPostProcessor) {
return x.json().then(jsonPostProcessor);
}
return x.json();
}));
});
}
asTextResponse() {
return __awaiter(this, arguments, void 0, function* (ensureSuccess = true) {
return this.execute(ensureSuccess, x => x.text());
});
}
asBlobResponse(ensureSuccess = true) {
return this.execute(ensureSuccess, x => x.blob());
}
dispatcher(dispatcher) {
return this.append({
dispatcher
});
}
withFetchProxy(fetchProxy) {
return this.append({
fetchProxy
});
}
execute() {
return __awaiter(this, arguments, void 0, function* (ensureSuccess = true, postProcessor) {
var _a, _b, _c, _e, _f, _g;
const env_1 = {
stack: [],
error: void 0,
hasError: false
};
try {
let {
log,
logError,
hideBusyIndicator
} = this.request;
const _d = __addDisposableResource(env_1, !hideBusyIndicator ? App.current.createBusyIndicator() : null, false);
try {
const {
headers,
fetchProxy,
jsonPostProcessor
} = this.request;
const r = yield (fetchProxy !== null && fetchProxy !== void 0 ? fetchProxy : fetch)(this.request.url, this.request);
if (ensureSuccess) {
if (r.status > 300) {
log = logError;
log === null || log === void 0 ? void 0 : log(`fetch: ${(_a = this.request.method) !== null && _a !== void 0 ? _a : "GET"} ${this.request.url}`);
if (log && headers) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
log === null || log === void 0 ? void 0 : log(`${key}: ${headers[key]}`);
}
}
}
log === null || log === void 0 ? void 0 : log(`${r.status} ${r.statusText || "Http Error"}`);
const type = r.headers.get("content-type");
if (/\/json/i.test(type)) {
const json = yield r.json();
log === null || log === void 0 ? void 0 : log(json);
const message = (_f = (_e = (_c = (_b = json.title) !== null && _b !== void 0 ? _b : json.detail) !== null && _c !== void 0 ? _c : json.message) !== null && _e !== void 0 ? _e : json.exceptionMessage) !== null && _f !== void 0 ? _f : "Json Server Error";
log = null;
logError = null;
throw new JsonError(message, json);
}
const text = yield r.text();
log === null || log === void 0 ? void 0 : log(text);
log = null;
logError = null;
throw new Error(`Fetch failed with error ${r.status} for ${this.request.url}\n${text}`);
}
}
log === null || log === void 0 ? void 0 : log(`${(_g = this.request.method) !== null && _g !== void 0 ? _g : "GET"} ${this.request.url}`);
if (log && headers) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
log === null || log === void 0 ? void 0 : log(`${key}: ${headers[key]}`);
}
}
}
const result = yield postProcessor(r, jsonPostProcessor);
if (log) {
log(`${r.status} ${r.statusText || "OK"}`);
log(result);
}
return {
result,
headers: r.headers,
status: r.status
};
} catch (error) {
log === null || log === void 0 ? void 0 : log(error);
throw error;
}
} catch (e_1) {
env_1.error = e_1;
env_1.hasError = true;
} finally {
__disposeResources(env_1);
}
});
}
append(r) {
let {
url
} = this.request;
const {
url: newUrl
} = r;
if (newUrl) {
if (!url) {
url = newUrl;
} else {
if (/^https?\:\/\//i.test(newUrl)) {
url = newUrl;
} else {
let fullUrl = url;
if (!/^https?\:\/\//i.test(url)) {
fullUrl = new URL(url, location.href).toString();
}
url = new URL(newUrl, fullUrl).toString();
}
}
}
return new FetchBuilder(Object.assign(Object.assign(Object.assign({}, this.request), r), {
url
}));
}
});
JsonError = class JsonError extends Error {
constructor(message, json) {
super(message);
this.json = json;
}
};
FetchBuilder.JsonError = JsonError;
}
};
});
//# sourceMappingURL=FetchBuilder.js.map