Skip to content

Commit dfb0b41

Browse files
committed
Adds custom hook for event extraction logic
Implements a new hook to manage event extraction, including service validation and handling API requests to extract incident data. This enhancement facilitates better organization of event-related functionality and improves user experience by ensuring that at least one service is provided before submission. Utilizes existing hooks for authentication, routing, and status management to streamline the overall process.
1 parent 33af3d4 commit dfb0b41

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { useRequest } from "ahooks";
2+
import { useState } from "react";
3+
import { useStatus } from "~/Services/Status";
4+
import { Models } from "~/Services/Status.Models";
5+
import { useAccessToken } from "../Auth/useAccessToken";
6+
import { useRouter } from "../Router";
7+
8+
/**
9+
* @author Aloento
10+
* @since 1.0.0
11+
* @version 0.1.0
12+
*/
13+
export function useEventExtract(event: Models.IEvent) {
14+
const [services, _setServices] = useState<Models.IRegionService[]>([]);
15+
const [valServices, setValServices] = useState<string>();
16+
function setServices(action: (curr: Models.IRegionService[]) => Models.IRegionService[] = (s) => s) {
17+
const updated = action(services);
18+
let err: boolean = false;
19+
20+
if (!updated || !updated.length) {
21+
setValServices("At least one service is required.");
22+
err = true;
23+
}
24+
25+
_setServices(updated);
26+
!err && setValServices(undefined);
27+
28+
return !err;
29+
}
30+
31+
const getToken = useAccessToken();
32+
const { Nav } = useRouter();
33+
const { Refresh } = useStatus();
34+
35+
const { runAsync, loading } = useRequest(async () => {
36+
if (!setServices()) {
37+
return false;
38+
}
39+
40+
const url = process.env.SD_BACKEND_URL!;
41+
42+
const body: Record<string, any> = {
43+
components: services.map(s => s.Id),
44+
}
45+
46+
const raw = await fetch(`${url}/v2/incidents/${event.Id}/extract`, {
47+
method: "POST",
48+
headers: {
49+
"Content-Type": "application/json",
50+
"Authorization": `Bearer ${getToken()}`
51+
},
52+
body: JSON.stringify(body)
53+
});
54+
55+
const res = await raw.json();
56+
const id = res.id;
57+
58+
if (id) {
59+
await Refresh();
60+
Nav(`/Event/${id}`);
61+
}
62+
63+
return true;
64+
}, {
65+
manual: true
66+
});
67+
68+
return {
69+
services,
70+
setServices,
71+
valServices,
72+
OnSubmit: runAsync,
73+
Loading: loading
74+
}
75+
}

0 commit comments

Comments
 (0)