tooot/src/api/tooot.ts

81 lines
1.9 KiB
TypeScript
Raw Normal View History

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'
2021-10-24 00:43:00 +02:00
import Constants from 'expo-constants'
2021-06-21 11:59:29 +02:00
import * as Sentry from 'sentry-expo'
2022-08-12 16:44:28 +02:00
import handleError, { ctx } from './handleError'
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
sentry?: boolean
}
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,
2022-01-04 09:09:45 +01:00
sentry = true
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(' -> ') : ''),
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: {
2022-05-05 00:52:57 +02:00
'Content-Type':
body && body instanceof FormData
? 'multipart/form-data'
: 'application/json',
2021-08-22 00:17:24 +02:00
'User-Agent': `tooot/${Constants.manifest?.version}`,
2021-06-21 11:59:29 +02:00
Accept: '*/*',
...headers
},
2022-02-08 22:19:24 +01:00
...(body && { data: body }),
validateStatus: status =>
url.includes('translate') ? status < 500 : status === 200
2021-06-21 11:59:29 +02:00
})
.then(response => {
return Promise.resolve({
body: response.data
})
})
.catch(error => {
2022-06-09 23:25:01 +02:00
if (sentry) {
2022-01-04 09:09:45 +01:00
Sentry.Native.setExtras({
API: 'tooot',
2022-05-17 23:18:49 +02:00
...(error?.response && { response: error.response }),
...(error?.request && { request: error.request })
2022-01-04 09:09:45 +01:00
})
2021-06-21 11:59:29 +02:00
Sentry.Native.captureException(error)
}
2022-08-12 16:44:28 +02:00
return handleError(error)
2021-06-21 11:59:29 +02:00
})
}
export default apiTooot