-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathadapter.ts
More file actions
86 lines (81 loc) · 2.75 KB
/
adapter.ts
File metadata and controls
86 lines (81 loc) · 2.75 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import PostRobot from "post-robot";
import {
AxiosError,
AxiosHeaders,
AxiosRequestConfig,
AxiosResponse,
} from "axios";
import { axiosToFetchResponse, fetchToAxiosConfig } from "./utils";
/**
* Dispatches a request using PostRobot.
* @param postRobot - The PostRobot instance.
* @returns A function that takes AxiosRequestConfig and returns a promise.
*/
export const dispatchAdapter =
(postRobot: typeof PostRobot) =>
(
config: AxiosRequestConfig
) => {
return new Promise((resolve, reject) => {
postRobot
.sendToParent("apiAdapter", config)
.then((event: unknown) => {
const { data: response } = event as { data: AxiosResponse };
if (response.status >= 400) {
return reject({ ...response, config });
}
resolve({
data: response.data,
status: response.status,
statusText: response.statusText,
headers: response.headers,
config: config,
});
})
.catch(() => {
return reject(
new AxiosError(
"Something went wrong with the request",
"ERR_INTERNAL_SERVER",
{
...config,
headers: config.headers as AxiosHeaders,
},
null,
undefined
)
);
});
});
};
/**
* Dispatches an API request using axios and PostRobot.
* @param url - The URL of the API endpoint.
* @param options - Optional request options.
* @returns A promise that resolves to a partial Response object.
*/
export const dispatchApiRequest = async (
url: string,
options?: RequestInit
): Promise<Response> => {
try {
const config = fetchToAxiosConfig(url, options);
const axiosResponse = (await dispatchAdapter(PostRobot)(
config
)) as AxiosResponse;
return axiosToFetchResponse(axiosResponse);
} catch (err: any) {
if (err.response) {
return new Response(err.response?.data, {
status: err.response.status,
statusText: err.response.statusText,
headers: err.response.headers,
});
}
return new Response(err.stack, {
status: err.status || 500,
statusText: err.message || "Internal Server Error",
headers: err.config.headers,
});
}
};