-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi-toast-plugin.ts
More file actions
66 lines (56 loc) · 1.65 KB
/
api-toast-plugin.ts
File metadata and controls
66 lines (56 loc) · 1.65 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import useToastStore from '@utils/stores/toast-store';
import { ZodiosPlugin } from '@zodios/core';
import { AxiosError } from 'axios';
import i18n from 'i18next';
const SKIP_ERROR_HANDLING_URLS = [''];
const SKIP_SUCCESS_HANDLING_URLS = [''];
const apiToastPlugin: ZodiosPlugin = {
name: 'apiToastPlugin',
error: async (api, config, err) => {
if (SKIP_ERROR_HANDLING_URLS.includes(config.url)) {
console.log('Skipping error handling for', config.url);
throw err;
}
if (err instanceof AxiosError) {
useToastStore.getState().setToast({
type: 'error',
message:
err.response?.data?.message || i18n.t('common:apiErrorDescription'),
});
}
throw err;
},
response: async (api, config, response) => {
if (SKIP_SUCCESS_HANDLING_URLS.includes(config.url)) {
console.log('Skipping success handling for', config.url);
return response;
}
// Skip handling GET requests
if (config.method?.toUpperCase() === 'GET') {
return response;
}
const getMessage = () => {
let message = '';
switch (config.method?.toUpperCase()) {
case 'POST':
message = i18n.t('common:createSuccess');
break;
case 'PUT':
message = i18n.t('common:updateSuccess');
break;
case 'DELETE':
message = i18n.t('common:deleteSuccess');
break;
}
return message;
};
if (response.status >= 200 && response.status < 300) {
useToastStore.getState().setToast({
type: 'success',
message: getMessage(),
});
}
return response;
},
};
export default apiToastPlugin;