-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathutils.js
More file actions
88 lines (77 loc) · 2.44 KB
/
utils.js
File metadata and controls
88 lines (77 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { LS_ACCESS_TOKEN_KEY } from './constants'
export const isString = s => ({}).toString.call(s) === '[object String]'
export function getTargetContainer(container) {
let targetContainer
if (container instanceof Element) {
targetContainer = container
} else if (isString(container)) {
targetContainer = document.getElementById(container)
} else {
targetContainer = document.createElement('div')
}
return targetContainer
}
export const Query = {
parse(search = window.location.search) {
if (!search) return {}
const queryString = search[0] === '?' ? search.substring(1) : search
const query = {}
queryString.split('&')
.forEach(queryStr => {
const [key, value] = queryStr.split('=')
if (key) query[key] = value
})
return query
},
stringify(query, prefix = '?') {
const queryString = Object.keys(query)
.map(key => `${key}=${encodeURIComponent(query[key] || '')}`)
.join('&')
return queryString ? prefix + queryString : ''
},
}
function ajaxFactory(method) {
return function(apiPath, data = {}, base = 'https://api.github.com') {
const req = new XMLHttpRequest()
const token = localStorage.getItem(LS_ACCESS_TOKEN_KEY)
let url = `${base}${apiPath}`
let body = null
if (method === 'GET' || method === 'DELETE') {
url += Query.stringify(data)
}
const p = new Promise((resolve, reject) => {
req.addEventListener('load', () => {
const contentType = req.getResponseHeader('content-type')
const res = req.responseText
if (!/json/.test(contentType)) {
resolve(res)
return
}
const data = req.responseText ? JSON.parse(res) : {}
if (data.message) {
reject(new Error(data.message))
} else {
resolve(data)
}
})
req.addEventListener('error', error => reject(error))
})
req.open(method, url, true)
req.setRequestHeader('Accept', 'application/vnd.github.squirrel-girl-preview, application/vnd.github.html+json')
if (token) {
req.setRequestHeader('Authorization', `token ${token}`)
}
if (method !== 'GET' && method !== 'DELETE') {
body = JSON.stringify(data)
req.setRequestHeader('Content-Type', 'application/json')
}
req.send(body)
return p
}
}
export const http = {
get: ajaxFactory('GET'),
post: ajaxFactory('POST'),
delete: ajaxFactory('DELETE'),
put: ajaxFactory('PUT'),
}