BackendSrv: Make it possible to pass options to .get|post|patch... methods (#51316)

* feat: make it possible to pass in `options` to `.get()`, `.post()`, etc methods

* feat(Datasource): make it possible to specify `optinos` for `getResource()` and `postResource()`

* fix(BackendSrv): use partial `BackendSrvRequest`

* feat(Datasource): make it possible to set `options` for resource requests

* refactor(BackendSrv): remove internal usage of `.request()`

* fix(GettingStarted): remove unnecessary import

* fix: fix type issues by typing the delete dashboard response

* refactor: use more strict types for `params`

By reusing the type of `BackendSrvRequest.params`

* refactor: make the options paramater partial

* fix: extract `data` from the fetch response

* docs: update the deprecation notice or `BackendSrv.request()`

* refactor: use `.request()` as if it was private

* refactor: remove unnecessary change
This commit is contained in:
Levente Balogh 2022-10-04 10:40:21 +02:00 committed by GitHub
parent 489b302c03
commit cc6fae18db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 63 additions and 56 deletions

View File

@ -1072,12 +1072,10 @@ exports[`better eslint`] = {
[0, 0, 0, "Unexpected any. Specify a different type.", "6"],
[0, 0, 0, "Unexpected any. Specify a different type.", "7"],
[0, 0, 0, "Unexpected any. Specify a different type.", "8"],
[0, 0, 0, "Unexpected any. Specify a different type.", "9"],
[0, 0, 0, "Unexpected any. Specify a different type.", "10"],
[0, 0, 0, "Do not use any type assertions.", "11"],
[0, 0, 0, "Do not use any type assertions.", "12"],
[0, 0, 0, "Unexpected any. Specify a different type.", "13"],
[0, 0, 0, "Do not use any type assertions.", "14"]
[0, 0, 0, "Do not use any type assertions.", "9"],
[0, 0, 0, "Do not use any type assertions.", "10"],
[0, 0, 0, "Unexpected any. Specify a different type.", "11"],
[0, 0, 0, "Do not use any type assertions.", "12"]
],
"packages/grafana-runtime/src/utils/analytics.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"]
@ -2870,8 +2868,7 @@ exports[`better eslint`] = {
[0, 0, 0, "Unexpected any. Specify a different type.", "14"],
[0, 0, 0, "Unexpected any. Specify a different type.", "15"],
[0, 0, 0, "Unexpected any. Specify a different type.", "16"],
[0, 0, 0, "Unexpected any. Specify a different type.", "17"],
[0, 0, 0, "Unexpected any. Specify a different type.", "18"]
[0, 0, 0, "Unexpected any. Specify a different type.", "17"]
],
"public/app/core/services/context_srv.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],

View File

@ -143,15 +143,16 @@ export function isFetchError(e: unknown): e is FetchError {
* @public
*/
export interface BackendSrv {
get<T = any>(url: string, params?: any, requestId?: string): Promise<T>;
delete<T = any>(url: string, data?: any): Promise<T>;
post<T = any>(url: string, data?: any): Promise<T>;
patch<T = any>(url: string, data?: any): Promise<T>;
put<T = any>(url: string, data?: any): Promise<T>;
get<T = any>(url: string, params?: any, requestId?: string, options?: Partial<BackendSrvRequest>): Promise<T>;
delete<T = any>(url: string, data?: any, options?: Partial<BackendSrvRequest>): Promise<T>;
post<T = any>(url: string, data?: any, options?: Partial<BackendSrvRequest>): Promise<T>;
patch<T = any>(url: string, data?: any, options?: Partial<BackendSrvRequest>): Promise<T>;
put<T = any>(url: string, data?: any, options?: Partial<BackendSrvRequest>): Promise<T>;
/**
* @deprecated Use the fetch function instead. If you prefer to work with a promise
* wrap the Observable returned by fetch with the lastValueFrom function.
* @deprecated Use the `.fetch()` function instead. If you prefer to work with a promise
* wrap the Observable returned by fetch with the lastValueFrom function, or use the get|delete|post|patch|put methods.
* This method is going to be private from Grafana 10.
*/
request<T = any>(options: BackendSrvRequest): Promise<T>;

View File

@ -1,4 +1,4 @@
import { merge, Observable, of } from 'rxjs';
import { lastValueFrom, merge, Observable, of } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import {
@ -24,6 +24,8 @@ import {
getGrafanaLiveSrv,
StreamingFrameOptions,
StreamingFrameAction,
BackendSrvRequest,
FetchResponse,
} from '../services';
import { BackendDataSourceResponse, toDataQueryResponse } from './queryResponse';
@ -219,29 +221,38 @@ class DataSourceWithBackend<
/**
* Make a GET request to the datasource resource path
*/
async getResource(path: string, params?: any): Promise<any> {
return getBackendSrv().get(`/api/datasources/${this.id}/resources/${path}`, params);
async getResource(
path: string,
params?: BackendSrvRequest['params'],
options?: Partial<BackendSrvRequest>
): Promise<any> {
return getBackendSrv().get(`/api/datasources/${this.id}/resources/${path}`, params, options?.requestId, options);
}
/**
* Send a POST request to the datasource resource path
*/
async postResource(path: string, body?: any): Promise<any> {
return getBackendSrv().post(`/api/datasources/${this.id}/resources/${path}`, { ...body });
async postResource(
path: string,
data?: BackendSrvRequest['data'],
options?: Partial<BackendSrvRequest>
): Promise<any> {
return getBackendSrv().post(`/api/datasources/${this.id}/resources/${path}`, { ...data }, options);
}
/**
* Run the datasource healthcheck
*/
async callHealthCheck(): Promise<HealthCheckResult> {
return getBackendSrv()
.request({ method: 'GET', url: `/api/datasources/${this.id}/health`, showErrorAlert: false })
.then((v) => {
return v as HealthCheckResult;
return lastValueFrom(
getBackendSrv().fetch<HealthCheckResult>({
method: 'GET',
url: `/api/datasources/${this.id}/health`,
showErrorAlert: false,
})
.catch((err) => {
return err.data as HealthCheckResult;
});
)
.then((v: FetchResponse) => v.data as HealthCheckResult)
.catch((err) => err.data as HealthCheckResult);
}
/**

View File

@ -407,24 +407,29 @@ export class BackendSrv implements BackendService {
return this.inspectorStream;
}
async get<T = any>(url: string, params?: any, requestId?: string): Promise<T> {
return await this.request({ method: 'GET', url, params, requestId });
async get<T = any>(
url: string,
params?: BackendSrvRequest['params'],
requestId?: BackendSrvRequest['requestId'],
options?: Partial<BackendSrvRequest>
) {
return this.request<T>({ ...options, method: 'GET', url, params, requestId });
}
async delete<T = any>(url: string, data?: any): Promise<T> {
return await this.request({ method: 'DELETE', url, data });
async delete<T = any>(url: string, data?: any, options?: Partial<BackendSrvRequest>) {
return this.request<T>({ ...options, method: 'DELETE', url, data });
}
async post<T = any>(url: string, data?: any): Promise<T> {
return await this.request({ method: 'POST', url, data });
async post<T = any>(url: string, data?: any, options?: Partial<BackendSrvRequest>) {
return this.request<T>({ ...options, method: 'POST', url, data });
}
async patch<T = any>(url: string, data: any): Promise<T> {
return await this.request({ method: 'PATCH', url, data });
async patch<T = any>(url: string, data: any, options?: Partial<BackendSrvRequest>) {
return this.request<T>({ ...options, method: 'PATCH', url, data });
}
async put<T = any>(url: string, data: any): Promise<T> {
return await this.request({ method: 'PUT', url, data });
async put<T = any>(url: string, data: any, options?: Partial<BackendSrvRequest>): Promise<T> {
return this.request<T>({ ...options, method: 'PUT', url, data });
}
withNoBackendCache(callback: any) {

View File

@ -10,6 +10,7 @@ import { LibraryElementExport } from '../../dashboard/components/DashExportModal
import { getLibraryPanel } from '../../library-panels/state/api';
import { LibraryElementDTO, LibraryElementKind } from '../../library-panels/types';
import { DashboardSearchHit } from '../../search/types';
import { DeleteDashboardResponse } from '../types';
import {
clearDashboard,
@ -275,11 +276,7 @@ export function saveDashboard(options: SaveDashboardCommand) {
}
function deleteFolder(uid: string, showSuccessAlert: boolean) {
return getBackendSrv().request({
method: 'DELETE',
url: `/api/folders/${uid}?forceDeleteRules=false`,
showSuccessAlert: showSuccessAlert,
});
return getBackendSrv().delete(`/api/folders/${uid}?forceDeleteRules=false`, undefined, { showSuccessAlert });
}
export function createFolder(payload: any) {
@ -304,11 +301,7 @@ export function getFolderById(id: number): Promise<{ id: number; title: string }
}
export function deleteDashboard(uid: string, showSuccessAlert: boolean) {
return getBackendSrv().request({
method: 'DELETE',
url: `/api/dashboards/uid/${uid}`,
showSuccessAlert: showSuccessAlert,
});
return getBackendSrv().delete<DeleteDashboardResponse>(`/api/dashboards/uid/${uid}`, { showSuccessAlert });
}
function executeInOrder(tasks: any[]) {

View File

@ -11,3 +11,9 @@ export interface Snapshot {
url?: string;
userId: number;
}
export type DeleteDashboardResponse = {
id: number;
message: string;
title: string;
};

View File

@ -71,15 +71,9 @@ export class GettingStarted extends PureComponent<PanelProps, State> {
dashboard?.removePanel(panel!);
backendSrv
.request({
method: 'PUT',
url: '/api/user/helpflags/1',
showSuccessAlert: false,
})
.then((res: any) => {
contextSrv.user.helpFlags1 = res.helpFlags1;
});
backendSrv.put('/api/user/helpflags/1', undefined, { showSuccessAlert: false }).then((res: any) => {
contextSrv.user.helpFlags1 = res.helpFlags1;
});
};
render() {