const g = typeof window !== 'undefined' ? window : self; /** * @private * @param {string} url * @returns {string} */ function combineUrl(url) { if (/^(https?|wss?|ftp):/.test(url)) { return url; } if (typeof g.consts === 'undefined') { return url; } return (g.consts.path || '') + url; } /** * @typedef RequestOptions * @property {string} [method] * @property {string} [accept] * @property {Object.} [customHeaders] * @property {RequestMode} [mode] * @property {AbortSignal | null} [signal] * @property {boolean} [diagnostic] * @property {(this: XMLHttpRequestUpload, e: ProgressEvent) => any} [progress] */ /** * @param {string} url * @param {RequestOptions} [options] * @returns {Promise} */ export function get(url, options) { return fetch(combineUrl(url), { method: options?.method || 'GET', headers: { ...options?.customHeaders, 'Accept': options?.accept ?? 'application/json' }, mode: options?.mode, signal: options?.signal, cache: 'default' }); } /** * @typedef DiagnosedResponse * @property {number} time * @property {Response} response */ /** * @param {string} url * @param {BodyInit | null} [data] * @param {RequestOptions} [options] * @returns {Promise} */ export function post(url, data, options) { const headers = options?.customHeaders ?? {}; if (data instanceof FormData) { // contentType = 'multipart/form-data'; } else { if (typeof data !== 'string') { data = JSON.stringify(data); } // contentType = 'application/json'; if (headers['Content-Type'] == null) { headers['Content-Type'] = 'application/json'; } } /** @type {RequestInit} */ const opts = { method: options?.method || 'POST', headers, body: data, signal: options?.signal, cache: 'no-cache' }; if (options?.diagnostic) { const started = new Date().getTime(); return new Promise((resolve, reject) => { fetch(combineUrl(url), opts).then(response => { resolve({ time: new Date().getTime() - started, response }); }).catch(reject); }); } return fetch(combineUrl(url), opts); } /** * @param {string} url * @param {FormData} data * @param {RequestOptions} options * @returns {Promise} */ export function upload(url, data, options) { return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.onreadystatechange = function () { if (this.readyState === XMLHttpRequest.DONE) { if (this.status === 200) { resolve(this); } else { reject(`${this.status} ${this.statusText}: ${this.responseText}`); } } }; if (typeof options.progress === 'function') { request.upload.addEventListener('progress', function (ev) { if (ev.lengthComputable) { options.progress?.call(this, ev); } }, false); } request.open('POST', combineUrl(url)); if (options.customHeaders != null) { for (let header of Object.entries(options.customHeaders)) { request.setRequestHeader(header[0], header[1]); } } request.send(data); }); }