|
|
|
@ -1,4 +1,11 @@ |
|
|
|
|
import { DataQueryError, LoadingState, PanelData } from '@grafana/data'; |
|
|
|
|
import { |
|
|
|
|
compareArrayValues, |
|
|
|
|
compareDataFrameStructures, |
|
|
|
|
DataFrame, |
|
|
|
|
DataQueryError, |
|
|
|
|
LoadingState, |
|
|
|
|
PanelData, |
|
|
|
|
} from '@grafana/data'; |
|
|
|
|
import { useEffect, useRef, useState } from 'react'; |
|
|
|
|
import { PanelModel } from '../../state'; |
|
|
|
|
import { Unsubscribable } from 'rxjs'; |
|
|
|
@ -14,16 +21,37 @@ interface UsePanelLatestData { |
|
|
|
|
/** |
|
|
|
|
* Subscribes and returns latest panel data from PanelQueryRunner |
|
|
|
|
*/ |
|
|
|
|
export const usePanelLatestData = (panel: PanelModel, options: GetDataOptions): UsePanelLatestData => { |
|
|
|
|
export const usePanelLatestData = ( |
|
|
|
|
panel: PanelModel, |
|
|
|
|
options: GetDataOptions, |
|
|
|
|
checkSchema?: boolean |
|
|
|
|
): UsePanelLatestData => { |
|
|
|
|
const querySubscription = useRef<Unsubscribable>(); |
|
|
|
|
const [latestData, setLatestData] = useState<PanelData>(); |
|
|
|
|
|
|
|
|
|
useEffect(() => { |
|
|
|
|
let last: DataFrame[] = []; |
|
|
|
|
let lastUpdate = 0; |
|
|
|
|
|
|
|
|
|
querySubscription.current = panel |
|
|
|
|
.getQueryRunner() |
|
|
|
|
.getData(options) |
|
|
|
|
.subscribe({ |
|
|
|
|
next: (data) => setLatestData(data), |
|
|
|
|
next: (data) => { |
|
|
|
|
if (checkSchema) { |
|
|
|
|
const sameStructure = compareArrayValues(last, data.series, compareDataFrameStructures); |
|
|
|
|
if (sameStructure) { |
|
|
|
|
const now = Date.now(); |
|
|
|
|
const elapsed = now - lastUpdate; |
|
|
|
|
if (elapsed < 10000) { |
|
|
|
|
return; // avoid updates if the schema has not changed for 10s
|
|
|
|
|
} |
|
|
|
|
lastUpdate = now; |
|
|
|
|
} |
|
|
|
|
last = data.series; |
|
|
|
|
} |
|
|
|
|
setLatestData(data); |
|
|
|
|
}, |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
return () => { |
|
|
|
|