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
41 lines (36 loc) · 1.04 KB
/
errors.ts
File metadata and controls
41 lines (36 loc) · 1.04 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
import { AxiosError } from 'axios'
import Bag from '@/plugins/bag'
import capitalize from '@/plugins/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(' '),
)
})
}
export const getErrorMessages = (error: AxiosError): ErrorMessages => {
const errors = new ErrorMessages()
if (
error === null ||
typeof (error.response?.data as any)?.data !== 'object' ||
(error.response?.data as any)?.data === null ||
error.response?.status !== 422
) {
return errors
}
Object.keys((error.response?.data as any).data).forEach((key: string) => {
errors.addMany(key, sanitize(key, (error.response?.data as any).data[key]))
})
return errors
}