import { Dispatch, SetStateAction } from "react" import { notification } from 'antd'; const notificationTypeDictionary = new Map([ ['error', {notifyInstance: notification.error, caption: 'Ошибка'}], ['warning', {notifyInstance: notification.warning, caption: 'Предупреждение'}], ['info', {notifyInstance: notification.info, caption: 'Инфо'}], ['open', {notifyInstance: notification.info, caption: ''}], ]) /** * Вызов оповещений всплывающим окошком. * @param body string или ReactNode * @param notifyType для параметра типа. Допустимые значение 'error', 'warning', 'info' */ export const notify = (body: string|any, notifyType:string ='info', other?: any) => { if(!body) return const instance = notificationTypeDictionary.get(notifyType) ?? notificationTypeDictionary.get('open') instance?.notifyInstance({ description: body, message: instance.caption, placement: "bottomRight", duration: 10, ...other }) } type asyncFunction = (...args:any) => Promise; export const invokeWebApiWrapperAsync = async (funcAsync: asyncFunction, setShowLoader: Dispatch>, errorNotifyText: string) => { if(setShowLoader) setShowLoader(true) try{ await funcAsync() } catch (ex) { if(process.env.NODE_ENV === 'development') console.error(ex) if(errorNotifyText) notify(errorNotifyText, 'error') } finally{ if(setShowLoader) setShowLoader(false) } } export const download = async (url:string, fileName?:string) => { const response = await fetch(url, { headers: { Authorization: 'Bearer ' + localStorage['token'] }, method: 'Get' }) if(response.status !== 200) throw response const requestFileName = decodeURI(fileName ??response.headers .get('content-disposition') ?.split(';') .splice(-1)[0] .split("'") .splice(-1)[0] ?? url.replace('\\','/') .split('/') .splice(-1)[0] ?? 'file') const blob = await response.blob() const reader = new FileReader(); reader.readAsDataURL(blob); reader.onload = function (e) { let a = document.createElement('a'); a.href = (e.target?.result?.toString() ?? ''); a.download = requestFileName; document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox a.click(); a.remove(); }; } export const upload = async (url:string, formData: FormData) => { await fetch(url, { headers: { Authorization: 'Bearer ' + localStorage['token'] }, method: 'Post', body: formData, }) } export const formatBytes = (bytes:number) => { if(bytes < 1024) return `${bytes.toFixed(0)}b` if(bytes < 1024*1024) return `${(bytes/1024).toFixed(2)}kb` else return `${(bytes/1024/1024).toFixed(2)}Mb` }