Skip to content

Commit 066c841

Browse files
committed
feat: add submit to API helper function
1 parent f3a5158 commit 066c841

File tree

1 file changed

+48
-0
lines changed
  • src/runtime/server/utils

1 file changed

+48
-0
lines changed

src/runtime/server/utils/api.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Submit to API helper function
2+
export const submitToAPI = async (
3+
apiKey: string,
4+
submitUrl: string,
5+
body: BodyInit | null | undefined,
6+
) => {
7+
let res: Response | null = null
8+
let isSubmitted = false
9+
let isError = false
10+
let errorMessage = ''
11+
12+
// Headers
13+
const headers = {
14+
'Content-Type': 'application/json',
15+
'Accept': 'application/json',
16+
'Authorization': `Bearer ${apiKey}`,
17+
}
18+
19+
// Pass body to a POST request
20+
try {
21+
res = await fetch(submitUrl, {
22+
method: 'POST',
23+
headers,
24+
body,
25+
})
26+
27+
// Mark the submission successful, otherwise return error state
28+
if (res.ok) {
29+
isSubmitted = true
30+
}
31+
else {
32+
throw new Error(`${res.status} Error`)
33+
}
34+
}
35+
catch (error) {
36+
isError = true
37+
if (error instanceof Error) {
38+
errorMessage = error.message
39+
}
40+
}
41+
42+
return {
43+
res,
44+
isSubmitted,
45+
isError,
46+
errorMessage,
47+
}
48+
}

0 commit comments

Comments
 (0)