Add some useful factory functions

This commit is contained in:
Фролов 2021-08-13 14:46:22 +05:00
parent 39f9f04c20
commit 60b33503b1
4 changed files with 62 additions and 67 deletions

View File

@ -1,3 +1,6 @@
import { Dispatch, SetStateAction } from "react"
import notify from "./notify"
export const RegExpIsFloat = /^[-+]?\d+\.?\d?$/ export const RegExpIsFloat = /^[-+]?\d+\.?\d?$/
/* /*
@ -47,12 +50,37 @@ export const makeColumnsPlanFact = (title:string, key:string|string[], columsOth
} }
} }
// const makePaginationObject = (paginationContainer, ...other) =>{ type PaginationContainer = {
// let page = 1 + Math.floor(paginationContainer.skip/paginationContainer.take); skip?: number;
// return { take?: number;
// ...other, count?: number;
// pageSize: paginationContainer.take, items?: any[] | null;
// total: paginationContainer.total, }
// current: page,
// } type asyncFunction = (...args:any) => Promise<any|void>;
// }
export const makePaginationObject = (paginationContainer:PaginationContainer, ...other:any) => {
let page = 1 + Math.floor((paginationContainer.skip??0) /(paginationContainer.take??1));
return {
...other,
pageSize: paginationContainer.take,
total: paginationContainer.count ?? paginationContainer.items?.length ?? 0,
current: page,
}
}
export const updateFromWebApiWrapperAsync = async (funcAsync: asyncFunction, setShowLoader: Dispatch<SetStateAction<boolean>>, errorNotifyText: string) => {
if(setShowLoader)
setShowLoader(true)
try{
await funcAsync()
} catch (ex) {
if(process.env.NODE_ENV === 'development')
console.log(ex)
if(errorNotifyText)
notify(errorNotifyText, 'error')
} finally{
if(setShowLoader)
setShowLoader(false)
}
}

View File

@ -3,7 +3,7 @@ import {Table} from "antd";
import moment from 'moment' import moment from 'moment'
import LoaderPortal from '../../components/LoaderPortal' import LoaderPortal from '../../components/LoaderPortal'
import notify from "../../components/notify" import {updateFromWebApiWrapperAsync} from '../../components/factory'
import {Subscribe} from '../../services/signalr' import {Subscribe} from '../../services/signalr'
import {MessageService} from '../../services/api' import {MessageService} from '../../services/api'
@ -54,21 +54,16 @@ export default function ActiveMessagesOnline({idWell}) {
} }
} }
useEffect(() => { useEffect(() => {
const update = async () => { updateFromWebApiWrapperAsync(
setLoader(true) async () => {
try {
const messages = await MessageService.getMessages(idWell, 0, 4) const messages = await MessageService.getMessages(idWell, 0, 4)
handleReceiveMessages(messages) handleReceiveMessages(messages)
} },
catch (ex) { setLoader,
notify(`Не удалось загрузить сообщения по скважине "${idWell}"`, 'error') `Не удалось загрузить сообщения по скважине "${idWell}"`,
console.log(ex) )
} return Subscribe('hubs/telemetry','ReceiveMessages', `well_${idWell}`, handleReceiveMessages)
setLoader(false)
return Subscribe('hubs/telemetry','ReceiveMessages', `well_${idWell}`, handleReceiveMessages)
}
update()
}, [idWell]) }, [idWell])
return (<LoaderPortal show={loader}> return (<LoaderPortal show={loader}>

View File

@ -10,7 +10,7 @@ import {UserOfWells} from './UserOfWells'
import LoaderPortal from '../../components/LoaderPortal' import LoaderPortal from '../../components/LoaderPortal'
import {Subscribe} from '../../services/signalr' import {Subscribe} from '../../services/signalr'
import {DataService} from '../../services/api' import {DataService} from '../../services/api'
import notify from "../../components/notify" import {updateFromWebApiWrapperAsync} from '../../components/factory'
import '../../styles/message.css' import '../../styles/message.css'
@ -138,7 +138,7 @@ const defaultChartInterval = '600'
export default function TelemetryView({idWell}) { export default function TelemetryView({idWell}) {
const [saubData, setSaubData] = useState([]) const [saubData, setSaubData] = useState([])
const [chartInterval, setChartInterval] = useState(defaultChartInterval) const [chartInterval, setChartInterval] = useState(defaultChartInterval)
const [loader, setLoader] = useState(false) const [showLoader, setShowLoader] = useState(false)
const options = timePeriodCollection.map((line) => <Option key={line.value}>{line.label}</Option>) const options = timePeriodCollection.map((line) => <Option key={line.value}>{line.label}</Option>)
@ -149,32 +149,20 @@ export default function TelemetryView({idWell}) {
} }
useEffect(() => { useEffect(() => {
const update = async () => { updateFromWebApiWrapperAsync(
setLoader(true) async () => {
try { const data = await DataService.getData(idWell, null, chartInterval)
const data = await DataService.getData(idWell)
handleReceiveDataSaub(data) handleReceiveDataSaub(data)
} catch (ex) { },
notify(`Не удалось получить данные по скважине "${idWell}"`, 'error') setShowLoader,
console.log(ex) `Не удалось получить данные по скважине "${idWell}"`,
} )
setLoader(false) return Subscribe('hubs/telemetry', 'ReceiveDataSaub', `well_${idWell}`, handleReceiveDataSaub)
return Subscribe('hubs/telemetry', 'ReceiveDataSaub', `well_${idWell}`, handleReceiveDataSaub)
}
update()
}, [idWell])
useEffect(() => {
setLoader(true)
DataService.getData(idWell, null, chartInterval)
.then(handleReceiveDataSaub)
.catch(error => console.error(error))
.finally(() => setLoader(false))
}, [idWell, chartInterval]) }, [idWell, chartInterval])
const colSpan = 24 / (paramsGroups.length) const colSpan = 24 / (paramsGroups.length)
return (<LoaderPortal show={loader}> return (<LoaderPortal show={showLoader}>
<Row style={{marginBottom: '1rem'}}> <Row style={{marginBottom: '1rem'}}>
<Col> <Col>
<ModeDisplay data={saubData}/> <ModeDisplay data={saubData}/>

View File

@ -2,7 +2,7 @@ import LoaderPortal from '../components/LoaderPortal'
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import {makeColumn, makeColumnsPlanFact, RegExpIsFloat} from '../components/factory' import {makeColumn, makeColumnsPlanFact, RegExpIsFloat} from '../components/factory'
import {WellSectionService} from '../services/api' import {WellSectionService} from '../services/api'
import notify from '../components/notify' import {updateFromWebApiWrapperAsync} from '../components/factory'
import { EditableTable } from '../components/EditableTable'; import { EditableTable } from '../components/EditableTable';
import { Input } from 'antd' import { Input } from 'antd'
@ -40,22 +40,6 @@ const columns = [
makeColumnsPlanFact('Скорость спуска обсадной колонны', 'casingDownSpeed', numericColumnOptions), makeColumnsPlanFact('Скорость спуска обсадной колонны', 'casingDownSpeed', numericColumnOptions),
] ]
const runAsyncFunc = async (funcAsync, setShowLoader, errorNotifyText) => {
if(setShowLoader)
setShowLoader(true)
try{
await funcAsync()
} catch (ex) {
if(process.env.NODE_ENV === 'development')
console.log(ex)
if(errorNotifyText)
notify(errorNotifyText, 'error')
} finally{
if(setShowLoader)
setShowLoader(false)
}
}
export default function WellStat({idWell}){ export default function WellStat({idWell}){
const [showLoader, setShowLoader] = useState(false) const [showLoader, setShowLoader] = useState(false)
const [items, setItems] = useState([]) const [items, setItems] = useState([])
@ -66,7 +50,7 @@ export default function WellStat({idWell}){
} }
useEffect(() => { useEffect(() => {
runAsyncFunc( updateFromWebApiWrapperAsync(
async () => { async () => {
const paginationContainer = await WellSectionService.getAll(idWell, 0, 1024) const paginationContainer = await WellSectionService.getAll(idWell, 0, 1024)
addKeysAndUpdateStateData(paginationContainer.items) addKeysAndUpdateStateData(paginationContainer.items)
@ -76,7 +60,7 @@ export default function WellStat({idWell}){
} ,[idWell]) } ,[idWell])
const onAdd = (item) => { const onAdd = (item) => {
runAsyncFunc( updateFromWebApiWrapperAsync(
async () => { async () => {
const updatedItems = await WellSectionService.insert(idWell, [item]) const updatedItems = await WellSectionService.insert(idWell, [item])
const newItems = [...items, ...updatedItems] const newItems = [...items, ...updatedItems]
@ -87,7 +71,7 @@ export default function WellStat({idWell}){
} }
const onEdit = (item) => { const onEdit = (item) => {
runAsyncFunc( updateFromWebApiWrapperAsync(
async () => { async () => {
const updatedItem = await WellSectionService.update(idWell, item.id, item) const updatedItem = await WellSectionService.update(idWell, item.id, item)
const newItems = [...items] const newItems = [...items]
@ -100,7 +84,7 @@ export default function WellStat({idWell}){
} }
const onDelete = (item) =>{ const onDelete = (item) =>{
runAsyncFunc( updateFromWebApiWrapperAsync(
async () => { async () => {
await WellSectionService.delete(idWell, [item.id]) await WellSectionService.delete(idWell, [item.id])
const newItems = [...items] const newItems = [...items]