tooot/src/utils/api/general.ts

57 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-02-08 19:22:20 +01:00
import { GLOBAL } from '@utils/storage'
2021-02-20 19:12:44 +01:00
import axios from 'axios'
2023-01-29 00:37:56 +01:00
import { ctx, handleError, PagedResponse, parseHeaderLinks, userAgent } from './helpers'
2023-01-29 15:32:40 +01:00
import { CONNECT_DOMAIN } from './helpers/connect'
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
2022-12-15 14:28:36 +01:00
}: Params): Promise<PagedResponse<T>> => {
2021-02-20 19:12:44 +01:00
console.log(
2023-01-08 16:59:35 +01:00
ctx.bgMagenta.bold(' General ') +
' ' +
domain +
' ' +
method +
2023-01-08 16:59:35 +01:00
ctx.magenta(' -> ') +
`/${url}` +
2023-01-08 16:59:35 +01:00
(params ? ctx.magenta(' -> ') : ''),
2021-02-20 19:12:44 +01:00
params ? params : ''
)
return axios({
timeout: method === 'post' ? 1000 * 60 : 1000 * 15,
method,
baseURL: `https://${GLOBAL.connect ? CONNECT_DOMAIN() : domain}`,
2021-02-20 19:12:44 +01:00
url,
params,
headers: {
Accept: 'application/json',
2022-11-05 01:11:09 +01:00
...userAgent,
2023-01-29 00:37:56 +01:00
...headers,
2023-01-29 15:32:40 +01:00
...(body && body instanceof FormData && { 'Content-Type': 'multipart/form-data' }),
...(GLOBAL.connect && { 'x-tooot-domain': domain })
2021-02-20 19:12:44 +01:00
},
2023-01-29 00:37:56 +01:00
data: body
2021-02-20 19:12:44 +01:00
})
2023-01-07 18:01:08 +01:00
.then(response => ({ body: response.data, links: parseHeaderLinks(response.headers.link) }))
.catch(handleError())
2021-02-20 19:12:44 +01:00
}
export default apiGeneral