1
|
|
|
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ |
2
|
|
|
/* eslint-disable import/prefer-default-export */ |
3
|
|
|
import { useContext } from "react"; |
4
|
|
|
import { getApplicantSkillsEndpoint } from "../api/applicantSkills"; |
5
|
|
|
import { ErrorContext } from "../components/ErrorContainer"; |
6
|
|
|
import { FetchError } from "../helpers/httpRequests"; |
7
|
|
|
import { useResource } from "./webResourceHooks"; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* If the error is a FetchError and the response body contains a message field, use that to construct the message. |
11
|
|
|
* Otherwise, simply use the error object's message. |
12
|
|
|
* @param error |
13
|
|
|
*/ |
14
|
|
|
const errorToMessage = async (error: Error | FetchError): Promise<string> => { |
15
|
|
|
if (error instanceof FetchError && error.response.status) { |
16
|
|
|
try { |
17
|
|
|
const responseBody = await error.response.json(); |
18
|
|
|
if (responseBody.message) { |
19
|
|
|
return `${error.response.status} - ${responseBody.message}`; |
20
|
|
|
} |
21
|
|
|
} catch (e) { |
22
|
|
|
// Can't parse response json body; fall through and return normal error message. |
23
|
|
|
} |
24
|
|
|
} |
25
|
|
|
return error.message; |
26
|
|
|
}; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* This hook returns a handleError function which tries to push the error into the ErrorContext queue. |
30
|
|
|
* If no ErrorContext Provider exists in the component hierarchy, simply nothing will happen. |
31
|
|
|
*/ |
32
|
|
|
const useErrorHandler = () => { |
33
|
|
|
const { dispatch } = useContext(ErrorContext); |
34
|
|
|
const handleError = (error: Error | FetchError) => { |
35
|
|
|
errorToMessage(error).then((message) => |
36
|
|
|
dispatch({ |
37
|
|
|
type: "push", |
38
|
|
|
payload: message, |
39
|
|
|
}), |
40
|
|
|
); |
41
|
|
|
}; |
42
|
|
|
return handleError; |
43
|
|
|
}; |
44
|
|
|
|
45
|
|
|
export const useApplicantSkillIds = (applicantId: number) => { |
46
|
|
|
const handleError = useErrorHandler(); |
47
|
|
|
return useResource<{ skill_ids: number[] }>( |
48
|
|
|
getApplicantSkillsEndpoint(applicantId), |
49
|
|
|
{ |
50
|
|
|
skill_ids: [], |
51
|
|
|
}, |
52
|
|
|
{ |
53
|
|
|
handleError, |
54
|
|
|
}, |
55
|
|
|
); |
56
|
|
|
}; |
57
|
|
|
|