Last active
June 16, 2021 14:16
-
-
Save MrThanlon/232ac1eeab73d318a5067ceecbec437a to your computer and use it in GitHub Desktop.
api.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* API description | |
*/ | |
import request from './request.js' | |
const handler = { | |
get(target, property) { | |
/* | |
if (property in target) { | |
return target[property] | |
}*/ | |
if ('_url' in target) { | |
target._url += `/${property}` | |
} else { | |
target._url = `/${property}` | |
} | |
return new Proxy(target, handler) | |
}, | |
apply(target, thisArg, argumentList) { | |
const url = target._url | |
target._url = '' | |
return request(argumentList[0], url, argumentList[0]) | |
} | |
} | |
export default new Proxy(() => {}, handler) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import api from './api.js' | |
// GET /user/profile | |
let res = await api.user.profile('get') | |
// POST /admin/login | |
let res = await api.admin.login('post', {username: 'mrthanlon', password: '***'}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* XHR package of Promise | |
*/ | |
/** | |
* request API | |
* @param url {string} | |
* @param method {string} | |
* @param data {Object} | |
* @param decode {boolean} | |
* @return {Promise} | |
*/ | |
export default function request(method, url, data) { | |
return new Promise((resolve, reject) => { | |
const xhr = new XMLHttpRequest() | |
xhr.open(method, url) | |
xhr.onload = () => { | |
if (xhr.status === 200) { | |
resolve(xhr.response) | |
} else { | |
reject() | |
} | |
} | |
xhr.onerror = xhr.onabort = () => { | |
reject() | |
} | |
if (data === undefined) { | |
xhr.send() | |
} else if (data instanceof FormData) { | |
xhr.send(data) | |
} else { | |
xhr.setRequestHeader('Content-Type', 'application/json') | |
xhr.send(JSON.stringify(data)) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment