kura
Version:
The FileSystem API abstraction library.
99 lines • 3.27 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.XHR = void 0;
const FileSystemConstants_1 = require("./FileSystemConstants");
const FileError_1 = require("./FileError");
class XHR {
constructor(key, fullPath, options) {
this.key = key;
this.fullPath = fullPath;
if (options == null) {
options = {};
}
if (!(0 <= options.timeout)) {
options.timeout = 3000;
}
if (options.requestHeaders == null) {
options.requestHeaders = {};
}
this.options = options;
}
async get(url, responseType) {
const { xhr, promise } = this.createXMLHttpRequest();
xhr.open("GET", url);
this.configure(xhr);
xhr.responseType = responseType;
xhr.send();
return await promise;
}
async post(url, content, type) {
await this.xhr("POST", url, content, type);
}
async put(url, content, type) {
await this.xhr("PUT", url, content, type);
}
configure(xhr) {
xhr.timeout = this.options.timeout;
if (this.options.requestHeaders) {
for (const [key, value] of Object.entries(this.options.requestHeaders)) {
xhr.setRequestHeader(key, value);
}
}
}
createXMLHttpRequest() {
const xhr = new XMLHttpRequest();
const promise = new Promise((resolve, reject) => {
xhr.onerror = () => {
if (!this.handled) {
reject(new Error(`${this.url}: ${xhr.status} (${xhr.statusText})`));
}
};
xhr.ontimeout = () => {
if (!this.handled) {
reject(new Error(`${this.url}: timeout`));
}
};
xhr.onabort = () => {
if (!this.handled) {
reject(new Error(`${this.url}: aborted`));
}
};
xhr.onreadystatechange = () => {
if (xhr.readyState !== XMLHttpRequest.DONE) {
return;
}
if ((200 <= xhr.status && xhr.status < 300) || xhr.status === 304) {
resolve(xhr.response);
}
else if (xhr.status === 404) {
reject(new FileError_1.NotFoundError(this.key, this.fullPath));
}
else {
reject(new Error(`${this.url}: ${xhr.status} (${xhr.statusText})`));
}
this.handled = true;
};
});
return { xhr, promise };
}
async xhr(method, url, content, type) {
const { xhr, promise } = this.createXMLHttpRequest();
this.handled = false;
this.url = url;
xhr.open(method, url);
this.configure(xhr);
if (!type) {
if (content instanceof Blob) {
type = content.type;
}
if (!type) {
type = FileSystemConstants_1.DEFAULT_CONTENT_TYPE;
}
}
xhr.setRequestHeader("Content-Type", type);
xhr.send(content);
await promise;
}
}
exports.XHR = XHR;
//# sourceMappingURL=XHR.js.map