tooot/src/utils/api/tooot.ts

66 lines
1.4 KiB
TypeScript
Raw Normal View History

import { mapEnvironment } from '@utils/helpers/checkEnvironment'
2021-06-21 11:59:29 +02:00
import axios from 'axios'
import { ctx, handleError, processBody, userAgent } from './helpers'
2021-06-21 11:59:29 +02:00
export type Params = {
2021-12-06 21:25:09 +01:00
method: 'get' | 'post' | 'put' | 'delete'
2021-06-21 11:59:29 +02:00
url: string
params?: {
[key: string]: string | number | boolean | string[] | number[] | boolean[]
}
headers?: { [key: string]: string }
body?: FormData | Object
}
2022-01-02 22:28:33 +01:00
export const TOOOT_API_DOMAIN = mapEnvironment({
release: 'api.tooot.app',
2022-06-01 00:33:59 +02:00
candidate: 'api-candidate.tooot.app',
2022-01-02 22:28:33 +01:00
development: 'api-development.tooot.app'
})
2021-06-21 11:59:29 +02:00
const apiTooot = async <T = unknown>({
method,
url,
params,
headers,
body
2021-06-21 11:59:29 +02:00
}: Params): Promise<{ body: T }> => {
console.log(
2023-01-08 16:59:35 +01:00
ctx.bgGreen.bold(' tooot ') +
' ' +
method +
ctx.green(' -> ') +
`/${url}` +
(params ? ctx.green(' -> ') : ''),
2021-06-21 11:59:29 +02:00
params ? params : ''
)
return axios({
2022-12-16 22:00:22 +01:00
timeout: method === 'post' ? 1000 * 60 : 1000 * 30,
2021-06-21 11:59:29 +02:00
method,
2021-12-06 21:25:09 +01:00
baseURL: `https://${TOOOT_API_DOMAIN}/`,
url: `${url}`,
2021-06-21 11:59:29 +02:00
params,
headers: {
Accept: 'application/json',
2022-11-05 01:11:09 +01:00
...userAgent,
2021-06-21 11:59:29 +02:00
...headers
},
data: processBody(body)
2021-06-21 11:59:29 +02:00
})
.then(response => {
return Promise.resolve({
body: response.data
})
})
.catch(
handleError({
message: 'API error',
captureRequest: { url, params, body },
captureResponse: true
})
)
2021-06-21 11:59:29 +02:00
}
export default apiTooot