bigbuffet-rw/packages/pl-fe/src/toast.tsx

88 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-12-20 07:47:02 -08:00
import React from 'react';
2022-12-21 11:14:31 -08:00
import toast from 'react-hot-toast';
import { defineMessages, MessageDescriptor } from 'react-intl';
2022-12-20 07:47:02 -08:00
import Toast from './components/ui/toast';
2022-12-20 07:47:02 -08:00
import { httpErrorMessages } from './utils/errors';
import type { PlfeResponse } from './api';
type ToastText = string | MessageDescriptor
type ToastType = 'success' | 'error' | 'info'
2022-12-20 07:47:02 -08:00
interface IToastOptions {
action?(): void;
actionLink?: string;
actionLabel?: ToastText;
duration?: number;
summary?: string;
2022-12-20 07:47:02 -08:00
}
const DEFAULT_DURATION = 4000;
const createToast = (type: ToastType, message: ToastText, opts?: IToastOptions) => {
const duration = opts?.duration || DEFAULT_DURATION;
2022-12-21 11:14:31 -08:00
toast.custom((t) => <Toast t={t} message={message} type={type} {...opts} />, {
2022-12-20 07:47:02 -08:00
duration,
});
};
const info = (message: ToastText, opts?: IToastOptions) =>
2022-12-20 07:47:02 -08:00
createToast('info', message, opts);
const success = (message: ToastText, opts?: IToastOptions) =>
2022-12-20 07:47:02 -08:00
createToast('success', message, opts);
const error = (message: ToastText, opts?: IToastOptions) =>
2022-12-20 07:47:02 -08:00
createToast('error', message, opts);
const messages = defineMessages({
unexpectedMessage: { id: 'alert.unexpected.message', defaultMessage: 'Something went wrong.' },
2022-12-20 07:47:02 -08:00
});
const showAlertForError = (networkError: { response: PlfeResponse }) => {
2022-12-20 07:47:02 -08:00
if (networkError?.response) {
const { json, status, statusText } = networkError.response;
2022-12-20 07:47:02 -08:00
if (status === 502) {
return error('The server is down');
}
if (status === 404 || status === 410) {
// Skip these errors as they are reflected in the UI
return null;
}
let message: string | undefined = statusText;
if (json?.error) {
message = json.error;
2022-12-20 07:47:02 -08:00
}
if (!message) {
message = httpErrorMessages.find((httpError) => httpError.code === status)?.description;
}
if (message) {
return error(message);
}
} else {
console.error(networkError);
return error(messages.unexpectedMessage);
}
};
2022-12-20 07:47:02 -08:00
export {
type ToastText,
type IToastOptions,
type ToastType,
};
2022-12-20 07:47:02 -08:00
export default {
info,
success,
error,
showAlertForError,
};