mirror of https://github.com/tooot-app/app
62 lines
1.6 KiB
Plaintext
62 lines
1.6 KiB
Plaintext
import store from 'src/stacks/common/store'
|
|
|
|
export async function client (instance, query, { body, ...customConfig } = {}) {
|
|
const state = store.getState().instanceInfo
|
|
|
|
let url
|
|
let authHeader
|
|
switch (instance.type) {
|
|
case 'local':
|
|
url = `https://${state.local}/${instance.endpoint}`
|
|
authHeader = {
|
|
Authorization: `Bearer ${state.localToken}`
|
|
}
|
|
break
|
|
case 'remote':
|
|
url = `https://${state.remote}/${instance.endpoint}`
|
|
authHeader = {}
|
|
break
|
|
default:
|
|
return Promise.reject('Instance type is not defined.')
|
|
}
|
|
|
|
const headers = { 'Content-Type': 'application/json', ...authHeader }
|
|
|
|
const config = {
|
|
method: body ? 'POST' : 'GET',
|
|
...customConfig,
|
|
headers: {
|
|
...headers,
|
|
...customConfig.headers
|
|
}
|
|
}
|
|
|
|
const queryString = query
|
|
? `?${query.map(({ key, value }) => `${key}=${value}`).join('&')}`
|
|
: ''
|
|
|
|
if (body) {
|
|
config.body = JSON.stringify(body)
|
|
}
|
|
|
|
let data
|
|
try {
|
|
const response = await fetch(`${url}${queryString}`, config)
|
|
data = await response.json()
|
|
if (response.ok) {
|
|
return { headers: response.headers, body: 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 })
|
|
}
|