100 lines
2.9 KiB
TypeScript
100 lines
2.9 KiB
TypeScript
import { useToast } from 'bootstrap-vue-next';
|
|
import type { Toast } from 'bootstrap-vue-next';
|
|
import { getCurrentInstance } from 'vue';
|
|
import { type Composer, useI18n } from 'vue-i18n';
|
|
import { VxeUI } from 'vxe-pc-ui';
|
|
|
|
export const useAlertService = () => {
|
|
const toast = useToast();
|
|
if (!toast) {
|
|
throw new Error('BootstrapVueNext toast component was not found');
|
|
}
|
|
const i18n = useI18n();
|
|
return new AlertService({
|
|
toast,
|
|
i18n,
|
|
});
|
|
};
|
|
|
|
export default class AlertService {
|
|
private toast: ReturnType<typeof useToast>;
|
|
private i18n: Composer;
|
|
|
|
constructor({ toast, i18n }: { toast: ReturnType<typeof useToast>; i18n: Composer }) {
|
|
this.toast = toast;
|
|
this.i18n = i18n;
|
|
}
|
|
|
|
public showInfo(toastMessage: string, toastOptions?: Partial<Toast>) {
|
|
VxeUI.modal.message({
|
|
id: 'showInfoMsg',
|
|
content: toastMessage,
|
|
status: 'info',
|
|
duration: toastOptions?.delay || 5000,
|
|
title: toastOptions?.title || 'Info',
|
|
iconStatus: 'vxe-icon-info-circle-fill text-primary',
|
|
});
|
|
}
|
|
|
|
public showSuccess(toastMessage: string) {
|
|
VxeUI.modal.message({
|
|
id: 'showSuccessMsg',
|
|
content: toastMessage,
|
|
status: 'success',
|
|
});
|
|
}
|
|
|
|
public showWarn(toastMessage: string) {
|
|
VxeUI.modal.message({
|
|
id: 'showWarnMsg',
|
|
content: toastMessage,
|
|
status: 'warning',
|
|
});
|
|
}
|
|
|
|
public showError(toastMessage: string) {
|
|
VxeUI.modal.message({
|
|
id: 'showErrorMsg',
|
|
content: toastMessage,
|
|
status: 'error',
|
|
});
|
|
}
|
|
|
|
public showHttpError(httpErrorResponse: any) {
|
|
let errorMessage: string | null = null;
|
|
switch (httpErrorResponse.status) {
|
|
case 0:
|
|
errorMessage = this.i18n.t('error.server.not.reachable').toString();
|
|
break;
|
|
|
|
case 400: {
|
|
const arr = Object.keys(httpErrorResponse.headers || {});
|
|
let entityKey: string | null = null;
|
|
for (const entry of arr) {
|
|
if (entry.toLowerCase().endsWith('app-error')) {
|
|
errorMessage = httpErrorResponse.headers[entry];
|
|
} else if (entry.toLowerCase().endsWith('app-params')) {
|
|
entityKey = httpErrorResponse.headers[entry];
|
|
}
|
|
}
|
|
if (errorMessage && entityKey) {
|
|
errorMessage = this.i18n.t(errorMessage, { entityName: this.i18n.t(`global.menu.entities.${entityKey}`) }).toString();
|
|
} else if (!errorMessage && httpErrorResponse.data?.message) {
|
|
errorMessage = this.i18n.t(httpErrorResponse.data.message).toString();
|
|
}
|
|
break;
|
|
}
|
|
|
|
case 404:
|
|
errorMessage = this.i18n.t('error.http.404').toString();
|
|
break;
|
|
|
|
default:
|
|
errorMessage = httpErrorResponse.data?.message
|
|
? this.i18n.t(httpErrorResponse.data.message).toString()
|
|
: this.i18n.t('error.default').toString();
|
|
}
|
|
this.showError(errorMessage || this.i18n.t('error.default').toString());
|
|
}
|
|
}
|