-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-request-handler.ts
More file actions
61 lines (54 loc) · 1.52 KB
/
api-request-handler.ts
File metadata and controls
61 lines (54 loc) · 1.52 KB
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
import { HttpClient, configHandler } from "@contentstack/cli-utilities";
import { formatErrors } from "./error-helper";
interface RequestParams {
orgUid: string;
method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
queryParams?: Record<string, any>;
payload?: any;
url: string;
}
export async function apiRequestHandler(params: RequestParams): Promise<any> {
const { orgUid, method, queryParams, payload, url } = params;
const authtoken = configHandler.get("authtoken");
const headers = {
organization_uid: orgUid,
authtoken,
};
const httpClient = new HttpClient();
httpClient.headers(headers);
if (queryParams) {
httpClient.queryParams(queryParams);
}
try {
let response;
switch (method) {
case "GET":
response = await httpClient.get(url);
break;
case "POST":
response = await httpClient.post(url, payload);
break;
case "PUT":
response = await httpClient.put(url, payload);
break;
case "DELETE":
response = await httpClient.delete(url);
break;
case "PATCH":
response = await httpClient.patch(url, payload);
break;
default:
throw new Error(`Unsupported HTTP method: ${method}`);
}
const { status, data } = response;
if (status >= 200 && status < 300) {
return data;
}
const errorMessage = data?.error
? formatErrors(data)
: data?.error_message || "Something went wrong";
throw errorMessage;
} catch (error) {
throw error;
}
}