Updated src/client/util
This commit is contained in:
parent
e931c568b5
commit
3296f8d2ba
|
@ -0,0 +1,23 @@
|
|||
/**
|
||||
* Short hand for document.createElement
|
||||
* @param {string} tagName Tag name
|
||||
* @param {object} attributes A key-value pair of DOM attributes
|
||||
* @return {HTMLElement}
|
||||
*/
|
||||
export const cE = (tagName, attributes = {}) => {
|
||||
const elem = document.createElement(tagName);
|
||||
for (const [name, value] of Object.entries(attributes)) {
|
||||
elem.setAttribute(name, value);
|
||||
}
|
||||
return elem;
|
||||
};
|
||||
/**
|
||||
* Short hand for document.querySelector and querySelectorAll
|
||||
* @param {string} selector a html selector
|
||||
* @return {Element|NodeListOf<Element>}
|
||||
*/
|
||||
export const qS = (selector) => {
|
||||
const results = document.querySelectorAll(selector);
|
||||
return results.length === 1 ? results[0] : results;
|
||||
}
|
||||
;
|
|
@ -0,0 +1,49 @@
|
|||
/**
|
||||
* @typedef {Object} RequestOptions
|
||||
* @property {Object<string, any>} [body] Request body
|
||||
* @property {string} [method] Request method
|
||||
* @property {XMLHttpRequestResponseType} [responseType] raw response
|
||||
*/
|
||||
|
||||
/** @type {RequestOptions} */
|
||||
const defaultOptions = {
|
||||
method: 'GET',
|
||||
responseType: 'text', // Text because we will need to substr it.
|
||||
};
|
||||
|
||||
/**
|
||||
* Make an HTTP request
|
||||
* @param {string} url
|
||||
* @param {RequestOptions} [userOptions]
|
||||
* @return {Promise} reqestPromise
|
||||
*/
|
||||
export async function request(url, userOptions={}) {
|
||||
const options = Object.assign({}, defaultOptions, userOptions);
|
||||
console.log(options);
|
||||
return new Promise((resolve, reject)=>{
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open(options.method, url);
|
||||
|
||||
xhr.responseType = options.responseType;
|
||||
|
||||
xhr.onload = function() {
|
||||
if (this.status < 400) {
|
||||
if (options.responseType !== 'text') {
|
||||
resolve(this.response);
|
||||
} else {
|
||||
resolve(JSON.parse(this.responseText.substr(2)));
|
||||
}
|
||||
} else {
|
||||
reject(JSON.parse(this.responseText));
|
||||
}
|
||||
};
|
||||
|
||||
if (options.method === 'POST') {
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.send(JSON.stringify(options.body));
|
||||
} else {
|
||||
xhr.send();
|
||||
}
|
||||
});
|
||||
}
|
||||
export default request;
|
Loading…
Reference in New Issue