obs-portal/frontend/src/api.js

54 lines
1.2 KiB
JavaScript
Raw Normal View History

2021-02-14 18:21:34 +00:00
import {stringifyParams} from 'query'
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'})
}
}
const api = new API()
export default api