tooot/src/api/general.ts

62 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-02-20 19:12:44 +01:00
import axios from 'axios'
2021-10-24 00:43:00 +02:00
import Constants from 'expo-constants'
2022-08-12 16:44:28 +02:00
import handleError, { ctx } from './handleError'
2021-02-20 19:12:44 +01:00
export type Params = {
method: 'get' | 'post' | 'put' | 'delete'
2021-05-09 21:59:03 +02:00
domain: string
2021-02-20 19:12:44 +01:00
url: string
params?: {
2021-03-17 15:30:28 +01:00
[key: string]: string | number | boolean | string[] | number[] | boolean[]
2021-02-20 19:12:44 +01:00
}
headers?: { [key: string]: string }
body?: FormData | Object
}
const apiGeneral = async <T = unknown>({
method,
domain,
url,
params,
headers,
2022-05-05 00:52:57 +02:00
body
2021-02-20 19:12:44 +01:00
}: Params): Promise<{ body: T }> => {
console.log(
ctx.bgGreen.bold(' API general ') +
' ' +
domain +
' ' +
method +
ctx.green(' -> ') +
`/${url}` +
(params ? ctx.green(' -> ') : ''),
params ? params : ''
)
return axios({
timeout: method === 'post' ? 1000 * 60 : 1000 * 15,
method,
baseURL: `https://${domain}/`,
url,
params,
headers: {
2022-05-05 00:52:57 +02:00
'Content-Type':
body && body instanceof FormData
? 'multipart/form-data'
: 'application/json',
2021-08-29 15:25:38 +02:00
'User-Agent': `tooot/${Constants.manifest?.version}`,
Accept: '*/*',
2021-02-20 19:12:44 +01:00
...headers
},
...(body && { data: body })
})
.then(response => {
return Promise.resolve({
body: response.data
})
})
2022-08-12 16:44:28 +02:00
.catch(handleError)
2021-02-20 19:12:44 +01:00
}
export default apiGeneral