Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * fetch util
- * @type {Object<rest>}
- * @typeof {function(api, param):object} rest
- * @param {string} api - absolute api
- * @param {object} param
- * @return {object} {response, error}
- */
- require('whatwg-fetch');
- export default (() => {
- function core(api, param) {
- // cookie
- param.credentials = 'include';
- return window.fetch(api, param)
- .then(res => res.json())
- .catch(error => {
- setTimeout(() => { throw new Error(error); });
- return { error: error.message };
- });
- };
- function serialize(obj) {
- return Object.keys(obj).map(p => `${encodeURIComponent(p)}=${encodeURIComponent([obj[p]])}`).join('&');
- };
- return {
- get(api, param) {
- return param ? core(`${api}?${serialize(param)}`, param) : core(`${api}`, {});
- },
- post(api, param = {}) {
- return core(`${api}`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(param)
- });
- },
- upload(api, param = {}) {
- return core(`${api}`, {
- method: 'POST',
- body: param
- });
- }
- };
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement