forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.ts
More file actions
47 lines (41 loc) · 1.08 KB
/
Copy patherrors.ts
File metadata and controls
47 lines (41 loc) · 1.08 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
import Bag from '~/utils/bag'
import { capitalize } from '~/utils/capitalize'
export class ErrorMessages extends Bag<string> {}
const sanitize = (key: string, values: Array<string>): Array<string> => {
return values.map((value: string) => {
return capitalize(
value
.split(key)
.join(key.replace('_', ' '))
.split('_')
.join(' ')
.split('-')
.join(' ')
.split(' char')
.join(' character')
.split(' field ')
.join(' '),
)
})
}
interface AxiosLikeError {
response?: {
data?: { data?: Record<string, string[]> }
status?: number
}
}
export const getErrorMessages = (error: AxiosLikeError): ErrorMessages => {
const errors = new ErrorMessages()
if (
error === null ||
typeof error.response?.data?.data !== 'object' ||
error.response?.data?.data === null ||
error.response?.status !== 422
) {
return errors
}
Object.keys(error.response.data.data).forEach((key: string) => {
errors.addMany(key, sanitize(key, error.response!.data!.data![key]))
})
return errors
}