tooot/src/api/client.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

export async function client (url, query, { body, ...customConfig } = {}) {
if (!url) {
return Promise.reject('Missing URL.')
2020-10-23 09:22:17 +02:00
}
const headers = { 'Content-Type': 'application/json' }
const config = {
method: body ? 'POST' : 'GET',
...customConfig,
headers: {
...headers,
...customConfig.headers
}
}
if (body) {
config.body = JSON.stringify(body)
}
let data
try {
const response = await fetch(
`https://${url}${
Object.keys(query).length
2020-10-23 09:22:17 +02:00
? `?${Object.keys(query)
.map(key => `${key}=${query[key]}`)
.join('&')}`
: ''
}`,
config
)
data = await response.json()
if (response.ok) {
return data
}
throw new Error(response.statusText)
} catch (err) {
return Promise.reject(err.message ? err.message : data)
}
}
client.get = function (instance, endpoint, query, customConfig = {}) {
return client(instance, endpoint, query, { ...customConfig, method: 'GET' })
}
client.post = function (instance, endpoint, query, body, customConfig = {}) {
return client(instance, endpoint, query, { ...customConfig, body })
}