-
Notifications
You must be signed in to change notification settings - Fork 25
/
HttpUtils.ts
56 lines (51 loc) · 1.97 KB
/
HttpUtils.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
import { fetch } from 'cross-fetch';
import { AuthenticationResponseWithJWT, JWTPayload, SIOPErrors } from '../types';
export async function postWithBearerToken(url: string, body: JWTPayload, bearerToken: string): Promise<Response> {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${bearerToken}`,
},
body: JSON.stringify(body),
});
if (!response || !response.status || (response.status !== 200 && response.status !== 201)) {
throw new Error(`${SIOPErrors.RESPONSE_STATUS_UNEXPECTED} ${response.status}:${response.statusText}, ${await response.text()}`);
}
return response;
} catch (error) {
throw new Error(`${(error as Error).message}`);
}
}
export async function postAuthenticationResponse(url: string, body: AuthenticationResponseWithJWT): Promise<Response> {
return postAuthenticationResponseJwt(url, body.jwt);
}
export async function postAuthenticationResponseJwt(url: string, jwt: string): Promise<Response> {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
body: `id_token=${jwt}`,
});
if (!response || !response.status || response.status < 200 || response.status >= 400) {
throw new Error(`${SIOPErrors.RESPONSE_STATUS_UNEXPECTED} ${response.status}:${response.statusText}, ${await response.text()}`);
}
return response;
} catch (error) {
throw new Error(`${(error as Error).message}`);
}
}
export async function getWithUrl(url: string): Promise<Response> {
return fetch(url)
.then((response: Response) => {
if (response.status >= 400) {
return Promise.reject(Error(`${SIOPErrors.RESPONSE_STATUS_UNEXPECTED} ${response.status}:${response.statusText} URL: ${url}`));
}
return response.json();
})
.catch((e) => {
return Promise.reject(Error(`${(e as Error).message}`));
});
}