-
Notifications
You must be signed in to change notification settings - Fork 23
/
HttpUtils.ts
executable file
·138 lines (124 loc) · 4.4 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
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
import { fetch } from 'cross-fetch';
import Debug from 'debug';
import { ContentType, SIOPErrors, SIOPResonse } from '../types';
const debug = Debug('sphereon:siopv2:http');
export const getJson = async <T>(
URL: string,
opts?: {
bearerToken?: string;
contentType?: string | ContentType;
accept?: string;
customHeaders?: HeadersInit;
exceptionOnHttpErrorStatus?: boolean;
}
): Promise<SIOPResonse<T>> => {
return await siopFetch(URL, undefined, { method: 'GET', ...opts });
};
export const formPost = async <T>(
url: string,
body: BodyInit,
opts?: {
bearerToken?: string;
contentType?: string | ContentType;
accept?: string;
customHeaders?: HeadersInit;
exceptionOnHttpErrorStatus?: boolean;
}
): Promise<SIOPResonse<T>> => {
return await post(url, body, opts?.contentType ? { ...opts } : { contentType: ContentType.FORM_URL_ENCODED, ...opts });
};
export const post = async <T>(
url: string,
body?: BodyInit,
opts?: {
bearerToken?: string;
contentType?: string | ContentType;
accept?: string;
customHeaders?: HeadersInit;
exceptionOnHttpErrorStatus?: boolean;
}
): Promise<SIOPResonse<T>> => {
return await siopFetch(url, body, { method: 'POST', ...opts });
};
const siopFetch = async <T>(
url: string,
body?: BodyInit,
opts?: {
method?: string;
bearerToken?: string;
contentType?: string | ContentType;
accept?: string;
customHeaders?: HeadersInit;
exceptionOnHttpErrorStatus?: boolean;
}
): Promise<SIOPResonse<T>> => {
if (!url || url.toLowerCase().startsWith('did:')) {
throw Error(`Invalid URL supplied. Expected a http(s) URL. Recieved: ${url}`);
}
const headers = opts?.customHeaders ? opts.customHeaders : {};
if (opts?.bearerToken) {
headers['Authorization'] = `Bearer ${opts.bearerToken}`;
}
const method = opts?.method ? opts.method : body ? 'POST' : 'GET';
const accept = opts?.accept ? opts.accept : 'application/json';
headers['Content-Type'] = opts?.contentType ? opts.contentType : method !== 'GET' ? 'application/json' : undefined;
headers['Accept'] = accept;
const payload: RequestInit = {
method,
headers,
body,
};
debug(`START fetching url: ${url}`);
if (body) {
debug(`Body:\r\n${JSON.stringify(body)}`);
}
debug(`Headers:\r\n${JSON.stringify(payload.headers)}`);
const origResponse = await fetch(url, payload);
const clonedResponse = origResponse.clone();
const success = origResponse && origResponse.status >= 200 && origResponse.status < 400;
const textResponseBody = await clonedResponse.text();
const isJSONResponse =
(accept === 'application/json' || origResponse.headers['Content-Type'] === 'application/json') && textResponseBody.trim().startsWith('{');
const responseBody = isJSONResponse ? JSON.parse(textResponseBody) : textResponseBody;
if (success || opts?.exceptionOnHttpErrorStatus) {
debug(`${success ? 'success' : 'error'} status: ${clonedResponse.status}, body:\r\n${JSON.stringify(responseBody)}`);
} else {
console.warn(`${success ? 'success' : 'error'} status: ${clonedResponse.status}, body:\r\n${JSON.stringify(responseBody)}`);
}
if (!success && opts?.exceptionOnHttpErrorStatus) {
const error = JSON.stringify(responseBody);
throw new Error(error === '{}' ? '{"error": "not found"}' : error);
}
debug(`END fetching url: ${url}`);
return {
origResponse,
successBody: success ? responseBody : undefined,
errorBody: !success ? responseBody : undefined,
};
};
export const getWithUrl = async <T>(url: string, textResponse?: boolean): Promise<T> => {
// try {
const response = await fetch(url);
if (response.status >= 400) {
return Promise.reject(Error(`${SIOPErrors.RESPONSE_STATUS_UNEXPECTED} ${response.status}:${response.statusText} URL: ${url}`));
}
if (textResponse === true) {
return (await response.text()) as unknown as T;
}
return await response.json();
/*} catch (e) {
return Promise.reject(Error(`${(e as Error).message}`));
}*/
};
export const fetchByReferenceOrUseByValue = async <T>(referenceURI: string, valueObject: T, textResponse?: boolean): Promise<T> => {
let response: T = valueObject;
if (referenceURI) {
try {
response = await getWithUrl(referenceURI, textResponse);
} catch (e) {
console.log(e);
throw new Error(`${SIOPErrors.REG_PASS_BY_REFERENCE_INCORRECTLY}: ${e.message}, URL: ${referenceURI}`);
}
}
return response;
};