| 37 | } |
| 38 | |
| 39 | function ajaxFactory(method) { |
| 40 | return function(apiPath, data = {}, base = 'https://api.github.com') { |
| 41 | const req = new XMLHttpRequest() |
| 42 | const token = localStorage.getItem(LS_ACCESS_TOKEN_KEY) |
| 43 | |
| 44 | let url = `${base}${apiPath}` |
| 45 | let body = null |
| 46 | if (method === 'GET' || method === 'DELETE') { |
| 47 | url += Query.stringify(data) |
| 48 | } |
| 49 | |
| 50 | const p = new Promise((resolve, reject) => { |
| 51 | req.addEventListener('load', () => { |
| 52 | const contentType = req.getResponseHeader('content-type') |
| 53 | const res = req.responseText |
| 54 | if (!/json/.test(contentType)) { |
| 55 | resolve(res) |
| 56 | return |
| 57 | } |
| 58 | const data = req.responseText ? JSON.parse(res) : {} |
| 59 | if (data.message) { |
| 60 | reject(new Error(data.message)) |
| 61 | } else { |
| 62 | resolve(data) |
| 63 | } |
| 64 | }) |
| 65 | req.addEventListener('error', error => reject(error)) |
| 66 | }) |
| 67 | req.open(method, url, true) |
| 68 | |
| 69 | req.setRequestHeader('Accept', 'application/vnd.github.squirrel-girl-preview, application/vnd.github.html+json') |
| 70 | if (token) { |
| 71 | req.setRequestHeader('Authorization', `token ${token}`) |
| 72 | } |
| 73 | if (method !== 'GET' && method !== 'DELETE') { |
| 74 | body = JSON.stringify(data) |
| 75 | req.setRequestHeader('Content-Type', 'application/json') |
| 76 | } |
| 77 | |
| 78 | req.send(body) |
| 79 | return p |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | export const http = { |
| 84 | get: ajaxFactory('GET'), |