1
0
mirror of https://github.com/tooot-app/app synced 2025-06-05 22:19:13 +02:00

Transform into TypeScript

This commit is contained in:
Zhiyuan Zheng
2020-10-31 21:04:46 +01:00
parent 698b54868e
commit d2cc643b9c
57 changed files with 935 additions and 646 deletions

View File

@ -1,61 +0,0 @@
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 })
}

View File

@ -1,14 +1,22 @@
import store from 'src/stacks/common/store'
import store, { RootState } from 'src/stacks/common/store'
import ky from 'ky'
export default async function client ({
method, // * get / post
instance, // * local / remote
endpoint, // * if url is empty
query, // object
body // object
}) {
const state = store.getState().instanceInfo
const client = async ({
method,
instance,
endpoint,
query,
body
}: {
method: 'get' | 'post'
instance: 'local' | 'remote'
endpoint: string
query?: {
[key: string]: string | number | boolean
}
body?: object
}): Promise<any> => {
const state: RootState['instanceInfo'] = store.getState().instanceInfo
let response
try {
@ -38,3 +46,5 @@ export default async function client ({
return Promise.reject({ body: response.error_message })
}
}
export default client