tooot/src/api/tooot.ts

74 lines
1.7 KiB
TypeScript
Raw Normal View History

import * as Sentry from '@sentry/react-native'
2022-01-02 22:28:33 +01:00
import { mapEnvironment } from '@utils/checkEnvironment'
2021-06-21 11:59:29 +02:00
import axios from 'axios'
2022-08-12 16:44:28 +02:00
import handleError, { ctx } from './handleError'
2022-11-05 01:11:09 +01:00
import { 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(
ctx.bgGreen.bold(' API tooot ') +
' ' +
method +
ctx.green(' -> ') +
`/${url}` +
(params ? ctx.green(' -> ') : ''),
2021-06-21 11:59:29 +02:00
params ? params : ''
)
return axios({
timeout: method === 'post' ? 1000 * 60 : 1000 * 15,
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: {
'Content-Type': body && body instanceof FormData ? 'multipart/form-data' : 'application/json',
2021-06-21 11:59:29 +02:00
Accept: '*/*',
2022-11-05 01:11:09 +01:00
...userAgent,
2021-06-21 11:59:29 +02:00
...headers
},
2022-11-05 01:11:09 +01:00
...(body && { data: body })
2021-06-21 11:59:29 +02:00
})
.then(response => {
return Promise.resolve({
body: response.data
})
})
.catch(error => {
Sentry.setExtras({
API: 'tooot',
request: { url, params, body },
...(error?.response && { response: error.response })
})
Sentry.captureMessage('API error', {
contexts: { errorObject: error }
})
2021-06-21 11:59:29 +02:00
2022-08-12 16:44:28 +02:00
return handleError(error)
2021-06-21 11:59:29 +02:00
})
}
export default apiTooot