tooot/src/api/client.js

44 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
}
}
2020-10-26 00:27:53 +01:00
const queryString = query
2020-10-28 00:02:37 +01:00
? `?${query.map(({ key, value }) => `${key}=${value}`).join('&')}`
2020-10-26 00:27:53 +01:00
: ''
2020-10-23 09:22:17 +02:00
if (body) {
config.body = JSON.stringify(body)
}
2020-10-26 00:27:53 +01:00
2020-10-23 09:22:17 +02:00
let data
try {
const response = await fetch(`${url}${queryString}`, config)
2020-10-23 09:22:17 +02:00
data = await response.json()
if (response.ok) {
return { headers: response.headers, body: data }
2020-10-23 09:22:17 +02:00
}
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 })
}