2021-02-14 18:21:34 +00:00
|
|
|
import {stringifyParams} from 'query'
|
|
|
|
|
2021-02-10 21:28:36 +00:00
|
|
|
class API {
|
|
|
|
setAuthorizationHeader(authorization) {
|
|
|
|
this.authorization = authorization
|
|
|
|
}
|
|
|
|
|
|
|
|
async fetch(url, options = {}) {
|
|
|
|
const response = await window.fetch('/api' + url, {
|
|
|
|
...options,
|
|
|
|
headers: {
|
|
|
|
...(options.headers || {}),
|
|
|
|
Authorization: this.authorization,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2021-02-14 18:21:34 +00:00
|
|
|
if (response.status === 200) {
|
|
|
|
return await response.json()
|
|
|
|
} else {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async post(url, {body: body_, ...options}) {
|
2021-02-17 20:50:18 +00:00
|
|
|
let body = body_
|
|
|
|
let headers = {...(options.headers || {})}
|
|
|
|
|
|
|
|
if (!(typeof body === 'string' || body instanceof FormData)) {
|
|
|
|
body = JSON.stringify(body)
|
|
|
|
headers['Content-Type'] = 'application/json'
|
|
|
|
}
|
|
|
|
|
2021-02-14 18:27:16 +00:00
|
|
|
return await this.fetch(url, {
|
|
|
|
...options,
|
|
|
|
body,
|
|
|
|
method: 'post',
|
2021-02-17 20:50:18 +00:00
|
|
|
headers
|
2021-02-14 18:21:34 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
async get(url, {query, ...options} = {}) {
|
|
|
|
const queryString = query ? stringifyParams(query) : null
|
|
|
|
return await this.fetch(url + (queryString ? '?' + queryString : ''), {method: 'get', ...options})
|
|
|
|
}
|
|
|
|
|
|
|
|
async delete(url, options = {}) {
|
2021-02-14 18:27:16 +00:00
|
|
|
return await this.get(url, {...options, method: 'delete'})
|
2021-02-10 21:28:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const api = new API()
|
|
|
|
|
|
|
|
export default api
|