-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathrequests.ts
206 lines (169 loc) · 4.81 KB
/
requests.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { Alert } from 'react-native'
import { Storage } from './state/cache'
import { compareSemver } from './utils'
export function objectToForm(obj: { [key: string | number]: any }) {
let form = new FormData()
Object.keys(obj).forEach((key) => form.append(key, obj[key]))
return form
}
export async function postForm(
url: string,
data?: { [key: string | number]: any },
token?: string,
contentType?: string
) {
// Send a POST request with data formatted with FormData returning JSON
let headers: { [key: string]: string } = {}
if (token) headers['Authorization'] = `Bearer ${token}`
if (contentType) headers['Content-Type'] = contentType
const resp = await fetch(url, {
method: 'POST',
body: data ? objectToForm(data) : undefined,
headers,
})
return resp
}
export async function postJson(
url: string,
data?: any,
token?: string,
customHeaders?: { [key: string]: string }
) {
// Send a POST request with data formatted with FormData returning JSON
let headers: { [key: string]: string } = customHeaders ? customHeaders : {}
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
headers['Accept'] = 'application/json'
headers['Content-Type'] = 'application/json'
const resp = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers,
})
return resp
}
export async function post(url: string, token?: string) {
const resp = await fetch(url, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : {},
})
return resp
}
export async function get(url: string, token?: string, data?: any) {
let completeURL
if (data) {
let params = new URLSearchParams(data)
completeURL = `${url}?${params.toString()}`
} else {
completeURL = url
}
const resp = await fetch(completeURL, {
method: 'GET',
redirect: 'follow',
headers: token ? { Authorization: `Bearer ${token}` } : {},
})
return resp
}
export async function getJSON(
url: string,
token?: string,
data?: any,
customHeaders?: { [key: string]: string }
) {
let completeURL
if (data) {
let params = new URLSearchParams(data)
completeURL = `${url}?${params.toString()}`
} else {
completeURL = url
}
let reqHeaders: HeadersInit = token ? { Authorization: `Bearer ${token}` } : {}
if (customHeaders) {
reqHeaders = { ...reqHeaders, ...customHeaders }
}
const resp = await fetch(completeURL, {
method: 'GET',
redirect: 'follow',
headers: reqHeaders,
})
return resp.json()
}
export function getJsonWithTimeout(
url: string,
token?: string,
data?: any,
customHeaders?: { [key: string]: string },
timeout = 5000
): Promise<Response> {
let completeURL
if (data) {
let params = new URLSearchParams(data)
completeURL = `${url}?${params.toString()}`
} else {
completeURL = url
}
let reqHeaders: HeadersInit = token ? { Authorization: `Bearer ${token}` } : {}
if (customHeaders) {
reqHeaders = { ...reqHeaders, ...customHeaders }
}
return Promise.race([
fetch(completeURL, {
method: 'GET',
redirect: 'follow',
headers: reqHeaders,
}),
new Promise<Response>((_, reject) => {
setTimeout(() => {
reject(new Error(`Request for ${url} timed out after ${timeout} milliseconds`))
}, timeout)
}),
])
}
export async function loginPreflightCheck(server: string) {
let url = 'https://' + server + '/api/nodeinfo/2.0.json'
try {
let res = await getJsonWithTimeout(url, undefined, false, undefined, 5000)
let json = await res.json()
if (!json) {
Alert.alert('Error', 'This server is not compatible or is unavailable.')
return false
}
if (!json.software || !json.software.name || !json.software.version) {
Alert.alert('Error', 'Cannot reach server. Invalid software')
return false
}
const validVersion = compareSemver(json.software.version, '0.12.3')
if (validVersion === -1) {
Alert.alert(
'Error',
'Invalid or outdated version, please ask your admin to update.'
)
return false
}
if (json.software.name != 'pixelfed') {
Alert.alert(
'Error',
'Invalid server type, this app is only compatible with Pixelfed'
)
return false
}
} catch (e) {
Alert.alert('Error', 'This server is not compatible or is unavailable.')
return false
}
return true
}
export async function verifyCredentials(domain: string, token: string) {
const resp = await get(
`https://${domain}/api/v1/accounts/verify_credentials?_pe=1`,
token
)
return resp.json()
}
export async function queryApi(endpoint: string, params = null) {
let server = Storage.getString('app.instance')
let token = Storage.getString('app.token')
let url = `https://${server}/${endpoint}`
return await getJSON(url, token, params)
}