Skip to content

Instantly share code, notes, and snippets.

@MrThanlon
Last active June 16, 2021 14:16
Show Gist options
  • Save MrThanlon/232ac1eeab73d318a5067ceecbec437a to your computer and use it in GitHub Desktop.
Save MrThanlon/232ac1eeab73d318a5067ceecbec437a to your computer and use it in GitHub Desktop.
api.js
/**
* 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)
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: '***'})
/**
* 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