Files
memberApp/src/vueLib/general/useNotify.ts
2025-11-11 08:10:24 +01:00

95 lines
2.2 KiB
TypeScript

import { getCurrentInstance } from 'vue';
import type { Response } from '../models/Response';
import { AxiosError } from 'axios';
export function useNotify() {
const instance = getCurrentInstance();
const $q = instance?.appContext.config.globalProperties.$q;
function NotifyResponse(
response: Response | string | AxiosError | undefined,
type?: 'warning' | 'error',
timeout: number = 5000,
) {
let color = 'green';
let icon = 'check_circle';
switch (type) {
case 'warning':
color = 'orange';
icon = 'warning';
break;
case 'error':
color = 'red';
icon = 'error';
break;
}
if (response) {
let message = '';
if (response instanceof AxiosError && response.response) {
if (response.response.data) {
const data = response.response.data as Response;
message = data.message;
}
} else {
message = typeof response === 'string' ? response : (response.message ?? '');
}
if (message === '') {
return;
}
color = typeof response === 'string' ? color : type === 'error' ? 'red' : color;
icon = typeof response === 'string' ? icon : type === 'error' ? 'error' : icon;
if (!$q) {
console.error(message);
return;
}
$q?.notify({
message: message,
color: color,
position: 'top',
icon: icon,
timeout: timeout,
actions: [
{
icon: 'close',
color: 'white',
dense: true,
round: true,
handler: () => {
/* just closes */
},
},
],
});
}
}
function NotifyDialog(title: string, text: string, okText?: string, cancelText?: string) {
return new Promise((resolve) => {
$q
?.dialog({
title: title,
message: text,
persistent: true,
ok: okText ?? 'OK',
cancel: cancelText ?? 'CANCEL',
})
.onOk(() => {
resolve(true);
})
.onCancel(() => {
resolve(false);
})
.onDismiss(() => {
resolve(false);
});
});
}
return {
NotifyDialog,
NotifyResponse,
};
}