|
1
|
import { ApiTestingOptions } from "types" |
|
2
|
|
|
3
|
export type useRequestRunnerProps = { |
|
4
|
pushLog: (...message: string[]) => void |
|
5
|
onFinish: (message: string, statusCode: string) => void |
|
6
|
replaceLog?: (message: string) => void |
|
7
|
} |
|
8
|
|
|
9
|
export const useRequestRunner = ({ |
|
10
|
pushLog, |
|
11
|
onFinish, |
|
12
|
replaceLog, |
|
13
|
}: useRequestRunnerProps) => { |
|
14
|
const runRequest = (apiRequestOptions: ApiTestingOptions) => { |
|
15
|
let requestUrl = apiRequestOptions.url |
|
16
|
if (apiRequestOptions.pathData) { |
|
17
|
Object.entries(apiRequestOptions.pathData).forEach(([key, value]) => { |
|
18
|
if (typeof value === "string") { |
|
19
|
requestUrl = requestUrl.replace(`{${key}}`, value) |
|
20
|
} |
|
21
|
}) |
|
22
|
} |
|
23
|
|
|
24
|
// check if there are query params |
|
25
|
if (apiRequestOptions.queryData) { |
|
26
|
requestUrl += `?${new URLSearchParams( |
|
27
|
apiRequestOptions.queryData as Record<string, string> |
|
28
|
).toString()}` |
|
29
|
} |
|
30
|
|
|
31
|
let responseCode = "" |
|
32
|
|
|
33
|
fetch(requestUrl, { |
|
34
|
method: apiRequestOptions.method, |
|
35
|
headers: { |
|
36
|
"Content-Type": "application/json", |
|
37
|
}, |
|
38
|
body: apiRequestOptions.bodyData |
|
39
|
? JSON.stringify(apiRequestOptions.bodyData) |
|
40
|
: undefined, |
|
41
|
}) |
|
42
|
.then(async (response) => { |
|
43
|
responseCode = `${response.status}` |
|
44
|
return response.json() |
|
45
|
}) |
|
46
|
.then((data) => { |
|
47
|
const stringifiedData = JSON.stringify(data, undefined, 2) |
|
48
|
if (replaceLog) { |
|
49
|
replaceLog(stringifiedData) |
|
50
|
} else { |
|
51
|
pushLog(stringifiedData) |
|
52
|
} |
|
53
|
}) |
|
54
|
.catch((error) => { |
|
55
|
pushLog(`\nAn error ocurred: ${JSON.stringify(error, undefined, 2)}`) |
|
56
|
if (responseCode === "404") { |
|
57
|
pushLog( |
|
58
|
`\nPossible Solutions:\n`, |
|
59
|
`- If this is a custom API route, make sure you added it at the correct path.`, |
|
60
|
`- If this API route accepts any parameters, such as an ID, make sure it exists\nin the Medusa application.` |
|
61
|
) |
|
62
|
return |
|
63
|
} |
|
64
|
|
|
65
|
if (!responseCode.length) { |
|
66
|
pushLog( |
|
67
|
`\nThis could be a CORS error. You can resolve it by adding\nthe docs' URLto your CORS configurations:\n`, |
|
68
|
`STORE_CORS=http://localhost:8000,https://docs.medusajs.com`, |
|
69
|
`ADMIN_CORS=http://localhost:7001,https://docs.medusajs.com` |
|
70
|
) |
|
71
|
} |
|
72
|
}) |
|
73
|
.finally(() => onFinish(`Finished running request.`, responseCode)) |
|
74
|
} |
|
75
|
|
|
76
|
return { |
|
77
|
runRequest, |
|
78
|
} |
|
79
|
} |