@grafana/data#PanelData TypeScript Examples
The following examples show how to use
@grafana/data#PanelData.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: actions.ts From grafana-chinese with Apache License 2.0 | 6 votes |
export function initPanelEditor(sourcePanel: PanelModel, dashboard: DashboardModel): ThunkResult<void> {
return dispatch => {
const panel = dashboard.initPanelEditor(sourcePanel);
const queryRunner = panel.getQueryRunner();
const querySubscription = queryRunner.getData().subscribe({
next: (data: PanelData) => dispatch(setEditorPanelData(data)),
});
dispatch(
updateEditorInitState({
panel,
sourcePanel,
querySubscription,
})
);
};
}
Example #2
Source File: BarGaugePanel.test.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
function createBarGaugePanelWithData(data: PanelData): ReactWrapper<PanelProps<BarGaugeOptions>> {
const timeRange = createTimeRange();
const options: BarGaugeOptions = {
displayMode: BarGaugeDisplayMode.Lcd,
fieldOptions: {
calcs: ['mean'],
defaults: {},
values: false,
overrides: [],
},
orientation: VizOrientation.Horizontal,
showUnfilled: true,
};
return mount<BarGaugePanel>(
<BarGaugePanel
id={1}
data={data}
timeRange={timeRange}
timeZone={'utc'}
options={options}
onOptionsChange={() => {}}
onChangeTimeRange={() => {}}
replaceVariables={s => s}
renderCounter={0}
width={532}
transparent={false}
height={250}
/>
);
}
Example #3
Source File: metrics_panel_ctrl.ts From grafana-chinese with Apache License 2.0 | 6 votes |
// Updates the response with information from the stream
panelDataObserver = {
next: (data: PanelData) => {
if (data.state === LoadingState.Error) {
this.loading = false;
this.processDataError(data.error);
}
// Ignore data in loading state
if (data.state === LoadingState.Loading) {
this.loading = true;
this.angularDirtyCheck();
return;
}
if (data.request) {
const { timeInfo } = data.request;
if (timeInfo) {
this.timeInfo = timeInfo;
}
}
if (data.timeRange) {
this.range = data.timeRange;
}
if (this.useDataFrames) {
this.handleDataFrames(data.series);
} else {
// Make the results look as if they came directly from a <6.2 datasource request
const legacy = data.series.map(v => toLegacyResponseData(v));
this.handleQueryResult({ data: legacy });
}
this.angularDirtyCheck();
},
};
Example #4
Source File: QueryStatus.test.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
describe('<QueryStatus />', () => {
it('should render with a latency', () => {
const res: PanelData = { series: [], state: LoadingState.Done, timeRange: {} as TimeRange };
const wrapper = shallow(<QueryStatus latency={0} queryResponse={res} />);
expect(wrapper.find('div').exists()).toBeTruthy();
});
it('should not render when query has not started', () => {
const res: PanelData = { series: [], state: LoadingState.NotStarted, timeRange: {} as TimeRange };
const wrapper = shallow(<QueryStatus latency={0} queryResponse={res} />);
expect(wrapper.getElement()).toBe(null);
});
});
Example #5
Source File: runRequest.ts From grafana-chinese with Apache License 2.0 | 6 votes |
export function preProcessPanelData(data: PanelData, lastResult: PanelData): PanelData {
const { series } = data;
// for loading states with no data, use last result
if (data.state === LoadingState.Loading && series.length === 0) {
if (!lastResult) {
lastResult = data;
}
return { ...lastResult, state: LoadingState.Loading };
}
// Make sure the data frames are properly formatted
const STARTTIME = performance.now();
const processedDataFrames = getProcessedDataFrames(series);
const STOPTIME = performance.now();
return {
...data,
series: processedDataFrames,
timings: { dataProcessingTime: STOPTIME - STARTTIME },
};
}
Example #6
Source File: PanelQueryRunner.ts From grafana-chinese with Apache License 2.0 | 6 votes |
private pipeToSubject(observable: Observable<PanelData>) {
if (this.subscription) {
this.subscription.unsubscribe();
}
this.subscription = observable.subscribe({
next: (data: PanelData) => {
this.lastResult = preProcessPanelData(data, this.lastResult);
this.subject.next(this.lastResult);
},
});
}
Example #7
Source File: PanelQueryRunner.ts From grafana-chinese with Apache License 2.0 | 6 votes |
/**
* Returns an observable that subscribes to the shared multi-cast subject (that reply last result).
*/
getData(transform = true): Observable<PanelData> {
if (transform) {
return this.subject.pipe(
map((data: PanelData) => {
if (this.hasTransformations()) {
const newSeries = transformDataFrame(this.transformations, data.series);
return { ...data, series: newSeries };
}
return data;
})
);
}
// Just pass it directly
return this.subject.pipe();
}
Example #8
Source File: QueryEditorRow.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
/**
* Get a version of the PanelData limited to the query we are looking at
*/
export function filterPanelDataToQuery(data: PanelData, refId: string): PanelData | undefined {
const series = data.series.filter(series => series.refId === refId);
// No matching series
if (!series.length) {
return undefined;
}
// Only say this is an error if the error links to the query
let state = LoadingState.Done;
const error = data.error && data.error.refId === refId ? data.error : undefined;
if (error) {
state = LoadingState.Error;
}
const timeRange = data.timeRange;
return {
...data,
state,
series,
error,
timeRange,
};
}
Example #9
Source File: QueryEditorRow.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
function notifyAngularQueryEditorsOfData(panel: PanelModel, data: PanelData, editor: AngularComponent) {
if (data === globalLastPanelDataCache) {
return;
}
globalLastPanelDataCache = data;
if (data.state === LoadingState.Done) {
const legacy = data.series.map(v => toLegacyResponseData(v));
panel.events.emit(PanelEvents.dataReceived, legacy);
} else if (data.state === LoadingState.Error) {
panel.events.emit(PanelEvents.dataError, data.error);
}
// Some query controllers listen to data error events and need a digest
// for some reason this needs to be done in next tick
setTimeout(editor.digest);
}
Example #10
Source File: PanelInspector.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
constructor(props: Props) {
super(props);
this.state = {
last: {} as PanelData,
data: [],
selected: 0,
tab: props.selectedTab || InspectTab.Data,
drawerWidth: '50%',
stats: { requestTime: 0, queries: 0, dataSources: 0, processingTime: 0 },
};
}
Example #11
Source File: PanelChromeAngular.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
onPanelDataUpdate(data: PanelData) {
let errorMessage: string | undefined;
if (data.state === LoadingState.Error) {
const { error } = data;
if (error) {
if (errorMessage !== error.message) {
errorMessage = error.message;
}
}
}
this.setState({ data, errorMessage });
}
Example #12
Source File: reducers.ts From grafana-chinese with Apache License 2.0 | 6 votes |
pluginsSlice = createSlice({
name: 'panelEditorNew',
initialState: initialState(),
reducers: {
updateEditorInitState: (state, action: PayloadAction<InitEditorPayload>) => {
state.getPanel = () => action.payload.panel;
state.getSourcePanel = () => action.payload.sourcePanel;
state.querySubscription = action.payload.querySubscription;
state.initDone = true;
state.isOpen = true;
},
setEditorPanelData: (state, action: PayloadAction<PanelData>) => {
state.getData = () => action.payload;
},
setDiscardChanges: (state, action: PayloadAction<boolean>) => {
state.shouldDiscardChanges = action.payload;
},
setPanelEditorUIState: (state, action: PayloadAction<Partial<PanelEditorUIState>>) => {
state.ui = { ...state.ui, ...action.payload };
},
closeCompleted: state => {
state.isOpen = false;
state.initDone = false;
},
},
})
Example #13
Source File: PanelChromeAngular.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
componentDidMount() {
const { panel } = this.props;
this.loadAngularPanel();
// subscribe to data events
const queryRunner = panel.getQueryRunner();
this.querySubscription = queryRunner.getData(false).subscribe({
next: (data: PanelData) => this.onPanelDataUpdate(data),
});
}
Example #14
Source File: QueryEditorRow.test.ts From grafana-chinese with Apache License 2.0 | 6 votes |
describe('filterPanelDataToQuery', () => {
const data: PanelData = {
state: LoadingState.Done,
series: [
toDataFrame({ refId: 'A', fields: [{ name: 'AAA' }], meta: {} }),
toDataFrame({ refId: 'B', fields: [{ name: 'B111' }], meta: {} }),
toDataFrame({ refId: 'B', fields: [{ name: 'B222' }], meta: {} }),
toDataFrame({ refId: 'B', fields: [{ name: 'B333' }], meta: {} }),
toDataFrame({ refId: 'C', fields: [{ name: 'CCCC' }], meta: { requestId: 'sub3' } }),
],
error: {
refId: 'B',
message: 'Error!!',
},
request: makePretendRequest('111', [
makePretendRequest('sub1'),
makePretendRequest('sub2'),
makePretendRequest('sub3'),
]),
timeRange: { from: dateTime(), to: dateTime(), raw: { from: 'now-1d', to: 'now' } },
};
it('should not have an error unless the refId matches', () => {
const panelData = filterPanelDataToQuery(data, 'A');
expect(panelData.series.length).toBe(1);
expect(panelData.series[0].refId).toBe('A');
expect(panelData.error).toBeUndefined();
});
it('should match the error to the query', () => {
const panelData = filterPanelDataToQuery(data, 'B');
expect(panelData.series.length).toBe(3);
expect(panelData.series[0].refId).toBe('B');
expect(panelData.error!.refId).toBe('B');
});
});
Example #15
Source File: runRequest.test.ts From grafana-chinese with Apache License 2.0 | 5 votes |
start() {
this.subscription = runRequest(this.ds, this.request).subscribe({
next: (data: PanelData) => {
this.results.push(data);
},
});
}
Example #16
Source File: PromExploreQueryEditor.test.tsx From grafana-chinese with Apache License 2.0 | 5 votes |
setup = (renderMethod: any, propOverrides?: object) => {
const datasourceMock: unknown = {};
const datasource: PrometheusDatasource = datasourceMock as PrometheusDatasource;
const onRunQuery = jest.fn();
const onChange = jest.fn();
const query: PromQuery = { expr: '', refId: 'A', interval: '1s' };
const data: PanelData = {
state: LoadingState.NotStarted,
series: [],
request: {
requestId: '1',
dashboardId: 1,
interval: '1s',
panelId: 1,
range: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
raw: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
},
},
scopedVars: {},
targets: [],
timezone: 'GMT',
app: 'Grafana',
startTime: 0,
},
timeRange: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
raw: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
},
},
};
const history: any[] = [];
const exploreMode = 'Metrics';
const props: any = {
query,
data,
datasource,
exploreMode,
history,
onChange,
onRunQuery,
};
Object.assign(props, propOverrides);
return renderMethod(<PromExploreQueryEditor {...props} />);
}
Example #17
Source File: LokiExploreQueryEditor.test.tsx From grafana-chinese with Apache License 2.0 | 5 votes |
setup = (renderMethod: any, propOverrides?: object) => {
const datasource: LokiDatasource = makeMockLokiDatasource({});
datasource.languageProvider = new LokiLanguageProvider(datasource);
const onRunQuery = jest.fn();
const onChange = jest.fn();
const query: LokiQuery = { expr: '', refId: 'A', maxLines: 0 };
const data: PanelData = {
state: LoadingState.NotStarted,
series: [],
request: {
requestId: '1',
dashboardId: 1,
interval: '1s',
panelId: 1,
range: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
raw: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
},
},
scopedVars: {},
targets: [],
timezone: 'GMT',
app: 'Grafana',
startTime: 0,
},
timeRange: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
raw: {
from: toUtc('2020-01-01', 'YYYY-MM-DD'),
to: toUtc('2020-01-02', 'YYYY-MM-DD'),
},
},
};
const history: any[] = [];
const exploreMode: ExploreMode = ExploreMode.Logs;
const props: any = {
query,
data,
datasource,
exploreMode,
history,
onChange,
onRunQuery,
};
Object.assign(props, { ...props, ...propOverrides });
return renderMethod(<LokiExploreQueryEditor {...props} />);
}
Example #18
Source File: runSharedRequest.ts From grafana-chinese with Apache License 2.0 | 5 votes |
function getQueryError(msg: string): PanelData {
return {
state: LoadingState.Error,
series: [],
error: { message: msg },
timeRange: DefaultTimeRange,
};
}
Example #19
Source File: runSharedRequest.ts From grafana-chinese with Apache License 2.0 | 5 votes |
export function runSharedRequest(options: QueryRunnerOptions): Observable<PanelData> {
return new Observable<PanelData>(subscriber => {
const dashboard = getDashboardSrv().getCurrent();
const listenToPanelId = getPanelIdFromQuery(options.queries);
if (!listenToPanelId) {
subscriber.next(getQueryError('Missing panel reference ID'));
return null;
}
const currentPanel = dashboard.getPanelById(options.panelId);
const listenToPanel = dashboard.getPanelById(listenToPanelId);
if (!listenToPanel) {
subscriber.next(getQueryError('Unknown Panel: ' + listenToPanelId));
return null;
}
const listenToRunner = listenToPanel.getQueryRunner();
const subscription = listenToRunner.getData(false).subscribe({
next: (data: PanelData) => {
subscriber.next(data);
},
});
// If we are in fullscreen the other panel will not execute any queries
// So we have to trigger it from here
if (currentPanel.fullscreen) {
const { datasource, targets } = listenToPanel;
const modified = {
...options,
datasource,
panelId: listenToPanelId,
queries: targets,
};
listenToRunner.run(modified);
}
return () => {
console.log('runSharedRequest unsubscribe');
subscription.unsubscribe();
};
});
}
Example #20
Source File: reducers.ts From grafana-chinese with Apache License 2.0 | 5 votes |
createEmptyQueryResponse = (): PanelData => ({
state: LoadingState.NotStarted,
request: {} as DataQueryRequest<DataQuery>,
series: [],
error: null,
timeRange: DefaultTimeRange,
})
Example #21
Source File: PanelChrome.tsx From grafana-chinese with Apache License 2.0 | 5 votes |
// Updates the response with information from the stream
// The next is outside a react synthetic event so setState is not batched
// So in this context we can only do a single call to setState
onDataUpdate(data: PanelData) {
if (!this.props.isInView) {
// Ignore events when not visible.
// The call will be repeated when the panel comes into view
return;
}
let { isFirstLoad } = this.state;
let errorMessage: string | undefined;
switch (data.state) {
case LoadingState.Loading:
// Skip updating state data if it is already in loading state
// This is to avoid rendering partial loading responses
if (this.state.data.state === LoadingState.Loading) {
return;
}
break;
case LoadingState.Error:
const { error } = data;
if (error) {
if (errorMessage !== error.message) {
errorMessage = error.message;
}
}
break;
case LoadingState.Done:
// If we are doing a snapshot save data in panel model
if (this.props.dashboard.snapshot) {
this.props.panel.snapshotData = data.series.map(frame => toDataFrameDTO(frame));
}
if (isFirstLoad) {
isFirstLoad = false;
}
break;
}
this.setState({ isFirstLoad, errorMessage, data });
}
Example #22
Source File: runRequest.ts From grafana-chinese with Apache License 2.0 | 5 votes |
/**
* This function handles the excecution of requests & and processes the single or multiple response packets into
* a combined PanelData response.
* It will
* * Merge multiple responses into a single DataFrame array based on the packet key
* * Will emit a loading state if no response after 50ms
* * Cancel any still running network requests on unsubscribe (using request.requestId)
*/
export function runRequest(datasource: DataSourceApi, request: DataQueryRequest): Observable<PanelData> {
let state: RunningQueryState = {
panelData: {
state: LoadingState.Loading,
series: [],
request: request,
timeRange: request.range,
},
packets: {},
};
// Return early if there are no queries to run
if (!request.targets.length) {
request.endTime = Date.now();
state.panelData.state = LoadingState.Done;
return of(state.panelData);
}
const dataObservable = callQueryMethod(datasource, request).pipe(
// Transform response packets into PanelData with merged results
map((packet: DataQueryResponse) => {
if (!isArray(packet.data)) {
throw new Error(`Expected response data to be array, got ${typeof packet.data}.`);
}
request.endTime = Date.now();
state = processResponsePacket(packet, state);
return state.panelData;
}),
// handle errors
catchError(err =>
of({
...state.panelData,
state: LoadingState.Error,
error: processQueryError(err),
})
),
tap(getAnalyticsProcessor(datasource)),
// finalize is triggered when subscriber unsubscribes
// This makes sure any still running network requests are cancelled
finalize(cancelNetworkRequestsOnUnsubscribe(request)),
// this makes it possible to share this observable in takeUntil
share()
);
// If 50ms without a response emit a loading state
// mapTo will translate the timer event into state.panelData (which has state set to loading)
// takeUntil will cancel the timer emit when first response packet is received on the dataObservable
return merge(timer(200).pipe(mapTo(state.panelData), takeUntil(dataObservable)), dataObservable);
}
Example #23
Source File: runRequest.test.ts From grafana-chinese with Apache License 2.0 | 5 votes |
results: PanelData[];
Example #24
Source File: analyticsProcessor.ts From grafana-chinese with Apache License 2.0 | 5 votes |
export function getAnalyticsProcessor(datasource: DataSourceApi) {
let done = false;
return (data: PanelData) => {
if (!data.request || done) {
return;
}
if (data.state !== LoadingState.Done && data.state !== LoadingState.Error) {
return;
}
const eventData: MetaAnalyticsEventPayload = {
datasourceName: datasource.name,
datasourceId: datasource.id,
panelId: data.request.panelId,
dashboardId: data.request.dashboardId,
// app: 'dashboard',
dataSize: 0,
duration: data.request.endTime - data.request.startTime,
eventName: 'data-request',
// sessionId: '',
};
// enrich with dashboard info
const dashboard = getDashboardSrv().getCurrent();
if (dashboard) {
eventData.dashboardId = dashboard.id;
eventData.dashboardName = dashboard.title;
eventData.dashboardUid = dashboard.uid;
eventData.folderName = dashboard.meta.folderTitle;
}
if (data.series && data.series.length > 0) {
// estimate size
eventData.dataSize = data.series.length;
}
if (data.error) {
eventData.error = data.error.message;
}
reportMetaAnalytics(eventData);
// this done check is to make sure we do not double emit events in case
// there are multiple responses with done state
done = true;
};
}
Example #25
Source File: PanelQueryRunner.ts From grafana-chinese with Apache License 2.0 | 5 votes |
pipeDataToSubject = (data: PanelData) => {
this.subject.next(data);
this.lastResult = data;
};
Example #26
Source File: PanelQueryRunner.ts From grafana-chinese with Apache License 2.0 | 5 votes |
private lastResult?: PanelData;
Example #27
Source File: PanelQueryRunner.ts From grafana-chinese with Apache License 2.0 | 5 votes |
private subject?: ReplaySubject<PanelData>;
Example #28
Source File: PanelQueryRunner.ts From grafana-chinese with Apache License 2.0 | 5 votes |
getLastResult(): PanelData {
return this.lastResult;
}
Example #29
Source File: QueriesTab.tsx From grafana-chinese with Apache License 2.0 | 5 votes |
componentDidMount() {
const { panel } = this.props;
const queryRunner = panel.getQueryRunner();
this.querySubscription = queryRunner.getData(false).subscribe({
next: (data: PanelData) => this.onPanelDataUpdate(data),
});
}