Chore: Remove angular dependency from backendSrv (#20999)

* Chore: Remove angular dependency from backendSrv

* Refactor: Naive soultion for logging out unauthorized users

* Refactor: Restructures to different streams

* Refactor: Restructures datasourceRequest

* Refactor: Flipped back if statement

* Refactor: Extracted getFromFetchStream

* Refactor: Extracts toFailureStream operation

* Refactor: Fixes issue when options.params contains arrays

* Refactor: Fixes broken test (but we need a lot more)

* Refactor: Adds explaining comments

* Refactor: Adds latest RxJs version so cancellations work

* Refactor: Cleans up the takeUntil code

* Refactor: Adds tests for request function

* Refactor: Separates into smaller functions

* Refactor: Adds last error tests

* Started to changed so we require getBackendSrv from the @grafana-runtime when applicable.

* Using the getBackendSrv from @grafana/runtime.

* Changed so we use the getBackendSrv from the @grafana-runtime when possible.

* Fixed so Server Admin -> Orgs works again.

* Removed unused dependency.

* Fixed digest issues on the Server Admin -> Users page.

* Fix: Fixes digest problems in Playlists

* Fix: Fixes digest issues in VersionHistory

* Tests: Fixes broken tests

* Fix: Fixes digest issues in Alerting => Notification channels

* Fixed digest issues on the Intive page.

* Fixed so we run digest after password reset email sent.

* Fixed digest issue when trying to sign up account.

* Fixed so the Server Admin -> Edit Org works with backendSrv

* Fixed so Server Admin -> Users works with backend srv.

* Fixed digest issues in Server Admin -> Orgs

* Fix: Fixes digest issues in DashList plugin

* Fixed digest issues on Server Admin -> users.

* Fix: Fixes digest issues with Snapshots

* Fixed digest issue when deleting a user.

* Fix: Fixes digest issues with dashLink

* Chore: Changes RxJs version to 6.5.4 which includes the same cancellation fix

* Fix: Fixes digest issue when toggling folder in manage dashboards

* Fix: Fixes bug in executeInOrder

* Fix: Fixes digest issue with CreateFolderCtrl and FolderDashboardsCtrl

* Fix: Fixes tslint error in test

* Refactor: Changes default behaviour for emitted messages as before migration

* Fix: Fixes various digest issues when saving, starring or deleting dashboards

* Fix: Fixes digest issues with FolderPickerCtrl

* Fixed digest issue.

* Fixed digest issues.

* Fixed issues with angular digest.

* Removed the this.digest pattern.

Co-authored-by: Hugo Häggmark <hugo.haggmark@gmail.com>
Co-authored-by: Marcus Andersson <systemvetaren@gmail.com>
This commit is contained in:
kay delaney
2020-01-21 09:08:07 +00:00
committed by Hugo Häggmark
parent 6ff315a299
commit cf2cc71393
122 changed files with 2856 additions and 2016 deletions

View File

@@ -2,11 +2,12 @@ import angular from 'angular';
import _ from 'lodash';
import { iconMap } from './DashLinksEditorCtrl';
import { LinkSrv } from 'app/features/panel/panellinks/link_srv';
import { BackendSrv } from 'app/core/services/backend_srv';
import { backendSrv } from 'app/core/services/backend_srv';
import { DashboardSrv } from '../../services/DashboardSrv';
import { PanelEvents } from '@grafana/data';
import { CoreEvents } from 'app/types';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { promiseToDigest } from '../../../../core/utils/promiseToDigest';
export type DashboardLink = { tags: any; target: string; keepTime: any; includeVars: any };
@@ -94,13 +95,7 @@ function dashLink($compile: any, $sanitize: any, linkSrv: LinkSrv) {
export class DashLinksContainerCtrl {
/** @ngInject */
constructor(
$scope: any,
$rootScope: GrafanaRootScope,
backendSrv: BackendSrv,
dashboardSrv: DashboardSrv,
linkSrv: LinkSrv
) {
constructor($scope: any, $rootScope: GrafanaRootScope, dashboardSrv: DashboardSrv, linkSrv: LinkSrv) {
const currentDashId = dashboardSrv.getCurrent().id;
function buildLinks(linkDef: any) {
@@ -154,26 +149,28 @@ export class DashLinksContainerCtrl {
}
$scope.searchDashboards = (link: DashboardLink, limit: any) => {
return backendSrv.search({ tag: link.tags, limit: limit }).then(results => {
return _.reduce(
results,
(memo, dash) => {
// do not add current dashboard
if (dash.id !== currentDashId) {
memo.push({
title: dash.title,
url: dash.url,
target: link.target === '_self' ? '' : link.target,
icon: 'fa fa-th-large',
keepTime: link.keepTime,
includeVars: link.includeVars,
});
}
return memo;
},
[]
);
});
return promiseToDigest($scope)(
backendSrv.search({ tag: link.tags, limit: limit }).then(results => {
return _.reduce(
results,
(memo, dash) => {
// do not add current dashboard
if (dash.id !== currentDashId) {
memo.push({
title: dash.title,
url: dash.url,
target: link.target === '_self' ? '' : link.target,
icon: 'fa fa-th-large',
keepTime: link.keepTime,
includeVars: link.includeVars,
});
}
return memo;
},
[]
);
})
);
};
$scope.fillDropdown = (link: { searchHits: any }) => {

View File

@@ -1,15 +1,17 @@
import { appEvents, contextSrv, coreModule } from 'app/core/core';
import { DashboardModel } from '../../state/DashboardModel';
import $ from 'jquery';
import _ from 'lodash';
import angular, { ILocationService } from 'angular';
import angular, { ILocationService, IScope } from 'angular';
import { e2e } from '@grafana/e2e';
import { appEvents, contextSrv, coreModule } from 'app/core/core';
import { DashboardModel } from '../../state/DashboardModel';
import config from 'app/core/config';
import { BackendSrv } from 'app/core/services/backend_srv';
import { backendSrv } from 'app/core/services/backend_srv';
import { DashboardSrv } from '../../services/DashboardSrv';
import { CoreEvents } from 'app/types';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { AppEvents } from '@grafana/data';
import { e2e } from '@grafana/e2e';
import { promiseToDigest } from '../../../../core/utils/promiseToDigest';
export class SettingsCtrl {
dashboard: DashboardModel;
@@ -26,11 +28,10 @@ export class SettingsCtrl {
/** @ngInject */
constructor(
private $scope: any,
private $scope: IScope & Record<string, any>,
private $route: any,
private $location: ILocationService,
private $rootScope: GrafanaRootScope,
private backendSrv: BackendSrv,
private dashboardSrv: DashboardSrv
) {
// temp hack for annotations and variables editors
@@ -234,10 +235,12 @@ export class SettingsCtrl {
}
deleteDashboardConfirmed() {
this.backendSrv.deleteDashboard(this.dashboard.uid, false).then(() => {
appEvents.emit(AppEvents.alertSuccess, ['Dashboard Deleted', this.dashboard.title + ' has been deleted']);
this.$location.url('/');
});
promiseToDigest(this.$scope)(
backendSrv.deleteDashboard(this.dashboard.uid, false).then(() => {
appEvents.emit(AppEvents.alertSuccess, ['Dashboard Deleted', this.dashboard.title + ' has been deleted']);
this.$location.url('/');
})
);
}
onFolderChange(folder: { id: number; title: string }) {

View File

@@ -1,10 +1,13 @@
import _ from 'lodash';
import { IScope } from 'angular';
import { AppEvents } from '@grafana/data';
import coreModule from 'app/core/core_module';
import appEvents from 'app/core/app_events';
import { BackendSrv } from 'app/core/services/backend_srv';
import { backendSrv } from 'app/core/services/backend_srv';
import { ValidationSrv } from 'app/features/manage-dashboards';
import { ContextSrv } from 'app/core/services/context_srv';
import { AppEvents } from '@grafana/data';
import { promiseToDigest } from '../../../../core/utils/promiseToDigest';
export class FolderPickerCtrl {
initialTitle: string;
@@ -28,7 +31,7 @@ export class FolderPickerCtrl {
dashboardId?: number;
/** @ngInject */
constructor(private backendSrv: BackendSrv, private validationSrv: ValidationSrv, private contextSrv: ContextSrv) {
constructor(private validationSrv: ValidationSrv, private contextSrv: ContextSrv, private $scope: IScope) {
this.isEditor = this.contextSrv.isEditor;
if (!this.labelClass) {
@@ -45,33 +48,35 @@ export class FolderPickerCtrl {
permission: 'Edit',
};
return this.backendSrv.get('api/search', params).then((result: any) => {
if (
this.isEditor &&
(query === '' ||
query.toLowerCase() === 'g' ||
query.toLowerCase() === 'ge' ||
query.toLowerCase() === 'gen' ||
query.toLowerCase() === 'gene' ||
query.toLowerCase() === 'gener' ||
query.toLowerCase() === 'genera' ||
query.toLowerCase() === 'general')
) {
result.unshift({ title: this.rootName, id: 0 });
}
return promiseToDigest(this.$scope)(
backendSrv.get('api/search', params).then((result: any) => {
if (
this.isEditor &&
(query === '' ||
query.toLowerCase() === 'g' ||
query.toLowerCase() === 'ge' ||
query.toLowerCase() === 'gen' ||
query.toLowerCase() === 'gene' ||
query.toLowerCase() === 'gener' ||
query.toLowerCase() === 'genera' ||
query.toLowerCase() === 'general')
) {
result.unshift({ title: this.rootName, id: 0 });
}
if (this.isEditor && this.enableCreateNew && query === '') {
result.unshift({ title: '-- New Folder --', id: -1 });
}
if (this.isEditor && this.enableCreateNew && query === '') {
result.unshift({ title: '-- New Folder --', id: -1 });
}
if (this.enableReset && query === '' && this.initialTitle !== '') {
result.unshift({ title: this.initialTitle, id: null });
}
if (this.enableReset && query === '' && this.initialTitle !== '') {
result.unshift({ title: this.initialTitle, id: null });
}
return _.map(result, item => {
return { text: item.title, value: item.id };
});
});
return _.map(result, item => {
return { text: item.title, value: item.id };
});
})
);
}
onFolderChange(option: { value: number; text: string }) {
@@ -105,13 +110,15 @@ export class FolderPickerCtrl {
evt.preventDefault();
}
return this.backendSrv.createFolder({ title: this.newFolderName }).then((result: { title: string; id: number }) => {
appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);
return promiseToDigest(this.$scope)(
backendSrv.createFolder({ title: this.newFolderName }).then((result: { title: string; id: number }) => {
appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);
this.closeCreateFolder();
this.folder = { text: result.title, value: result.id };
this.onFolderChange(this.folder);
});
this.closeCreateFolder();
this.folder = { text: result.title, value: result.id };
this.onFolderChange(this.folder);
})
);
}
cancelCreateFolder(evt: any) {

View File

@@ -96,7 +96,7 @@ export class SaveDashboardModalCtrl {
this.selectors = e2e.pages.SaveDashboardModal.selectors;
}
save() {
save(): void | Promise<any> {
if (!this.saveForm.$valid) {
return;
}

View File

@@ -1,18 +1,19 @@
import angular, { ILocationService } from 'angular';
import angular, { ILocationService, IScope } from 'angular';
import _ from 'lodash';
import { BackendSrv } from 'app/core/services/backend_srv';
import { getBackendSrv } from '@grafana/runtime';
import { TimeSrv } from '../../services/TimeSrv';
import { DashboardModel } from '../../state/DashboardModel';
import { PanelModel } from '../../state/PanelModel';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { promiseToDigest } from '../../../../core/utils/promiseToDigest';
export class ShareSnapshotCtrl {
/** @ngInject */
constructor(
$scope: any,
$scope: IScope & Record<string, any>,
$rootScope: GrafanaRootScope,
$location: ILocationService,
backendSrv: BackendSrv,
$timeout: any,
timeSrv: TimeSrv
) {
@@ -38,10 +39,14 @@ export class ShareSnapshotCtrl {
];
$scope.init = () => {
backendSrv.get('/api/snapshot/shared-options').then((options: { [x: string]: any }) => {
$scope.sharingButtonText = options['externalSnapshotName'];
$scope.externalEnabled = options['externalEnabled'];
});
promiseToDigest($scope)(
getBackendSrv()
.get('/api/snapshot/shared-options')
.then((options: { [x: string]: any }) => {
$scope.sharingButtonText = options['externalSnapshotName'];
$scope.externalEnabled = options['externalEnabled'];
})
);
};
$scope.apiUrl = '/api/snapshots';
@@ -75,16 +80,20 @@ export class ShareSnapshotCtrl {
external: external,
};
backendSrv.post($scope.apiUrl, cmdData).then(
(results: { deleteUrl: any; url: any }) => {
$scope.loading = false;
$scope.deleteUrl = results.deleteUrl;
$scope.snapshotUrl = results.url;
$scope.step = 2;
},
() => {
$scope.loading = false;
}
promiseToDigest($scope)(
getBackendSrv()
.post($scope.apiUrl, cmdData)
.then(
(results: { deleteUrl: any; url: any }) => {
$scope.loading = false;
$scope.deleteUrl = results.deleteUrl;
$scope.snapshotUrl = results.url;
$scope.step = 2;
},
() => {
$scope.loading = false;
}
)
);
};
@@ -152,9 +161,13 @@ export class ShareSnapshotCtrl {
};
$scope.deleteSnapshot = () => {
backendSrv.get($scope.deleteUrl).then(() => {
$scope.step = 3;
});
promiseToDigest($scope)(
getBackendSrv()
.get($scope.deleteUrl)
.then(() => {
$scope.step = 3;
})
);
};
}
}

View File

@@ -1,6 +1,8 @@
import _ from 'lodash';
import { IScope } from 'angular';
import { HistoryListCtrl } from './HistoryListCtrl';
import { versions, compare, restore } from './__mocks__/history';
import { compare, restore, versions } from './__mocks__/history';
import { CoreEvents } from 'app/types';
describe('HistoryListCtrl', () => {
@@ -12,6 +14,7 @@ describe('HistoryListCtrl', () => {
let historySrv: any;
let $rootScope: any;
const $scope: IScope = ({ $evalAsync: jest.fn() } as any) as IScope;
let historyListCtrl: any;
beforeEach(() => {
historySrv = {
@@ -28,7 +31,7 @@ describe('HistoryListCtrl', () => {
beforeEach(() => {
historySrv.getHistoryList = jest.fn(() => Promise.resolve({}));
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, $scope);
historyListCtrl.dashboard = {
id: 2,
@@ -84,7 +87,7 @@ describe('HistoryListCtrl', () => {
beforeEach(async () => {
historySrv.getHistoryList = jest.fn(() => Promise.reject(new Error('HistoryListError')));
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, $scope);
await historyListCtrl.getLog();
});
@@ -127,7 +130,7 @@ describe('HistoryListCtrl', () => {
historySrv.getHistoryList = jest.fn(() => Promise.resolve(versionsResponse));
historySrv.calculateDiff = jest.fn(() => Promise.resolve({}));
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, $scope);
historyListCtrl.dashboard = {
id: 2,
@@ -260,7 +263,7 @@ describe('HistoryListCtrl', () => {
historySrv.getHistoryList = jest.fn(() => Promise.resolve(versionsResponse));
historySrv.restoreDashboard = jest.fn(() => Promise.resolve());
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, $scope);
historyListCtrl.dashboard = {
id: 1,
@@ -279,7 +282,7 @@ describe('HistoryListCtrl', () => {
beforeEach(async () => {
historySrv.getHistoryList = jest.fn(() => Promise.resolve(versionsResponse));
historySrv.restoreDashboard = jest.fn(() => Promise.resolve());
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, $scope);
historySrv.restoreDashboard = jest.fn(() => Promise.reject(new Error('RestoreError')));
historyListCtrl.restoreConfirm(RESTORE_ID);
await historyListCtrl.getLog();

View File

@@ -1,12 +1,13 @@
import _ from 'lodash';
import angular, { ILocationService } from 'angular';
import angular, { ILocationService, IScope } from 'angular';
import locationUtil from 'app/core/utils/location_util';
import { DashboardModel } from '../../state/DashboardModel';
import { HistoryListOpts, RevisionsModel, CalculateDiffOptions, HistorySrv } from './HistorySrv';
import { dateTime, toUtc, DateTimeInput, AppEvents } from '@grafana/data';
import { CalculateDiffOptions, HistoryListOpts, HistorySrv, RevisionsModel } from './HistorySrv';
import { AppEvents, dateTime, DateTimeInput, toUtc } from '@grafana/data';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { CoreEvents } from 'app/types';
import { promiseToDigest } from '../../../../core/utils/promiseToDigest';
export class HistoryListCtrl {
appending: boolean;
@@ -30,7 +31,7 @@ export class HistoryListCtrl {
private $rootScope: GrafanaRootScope,
private $location: ILocationService,
private historySrv: HistorySrv,
public $scope: any
public $scope: IScope
) {
this.appending = false;
this.diff = 'basic';
@@ -108,18 +109,20 @@ export class HistoryListCtrl {
diffType: diff,
};
return this.historySrv
.calculateDiff(options)
.then((response: any) => {
// @ts-ignore
this.delta[this.diff] = response;
})
.catch(() => {
this.mode = 'list';
})
.finally(() => {
this.loading = false;
});
return promiseToDigest(this.$scope)(
this.historySrv
.calculateDiff(options)
.then((response: any) => {
// @ts-ignore
this.delta[this.diff] = response;
})
.catch(() => {
this.mode = 'list';
})
.finally(() => {
this.loading = false;
})
);
}
getLog(append = false) {
@@ -130,25 +133,27 @@ export class HistoryListCtrl {
start: this.start,
};
return this.historySrv
.getHistoryList(this.dashboard, options)
.then((revisions: any) => {
// set formatted dates & default values
for (const rev of revisions) {
rev.createdDateString = this.formatDate(rev.created);
rev.ageString = this.formatBasicDate(rev.created);
rev.checked = false;
}
return promiseToDigest(this.$scope)(
this.historySrv
.getHistoryList(this.dashboard, options)
.then((revisions: any) => {
// set formatted dates & default values
for (const rev of revisions) {
rev.createdDateString = this.formatDate(rev.created);
rev.ageString = this.formatBasicDate(rev.created);
rev.checked = false;
}
this.revisions = append ? this.revisions.concat(revisions) : revisions;
})
.catch((err: any) => {
this.loading = false;
})
.finally(() => {
this.loading = false;
this.appending = false;
});
this.revisions = append ? this.revisions.concat(revisions) : revisions;
})
.catch((err: any) => {
this.loading = false;
})
.finally(() => {
this.loading = false;
this.appending = false;
})
);
}
isLastPage() {
@@ -183,17 +188,19 @@ export class HistoryListCtrl {
restoreConfirm(version: number) {
this.loading = true;
return this.historySrv
.restoreDashboard(this.dashboard, version)
.then((response: any) => {
this.$location.url(locationUtil.stripBaseFromUrl(response.url)).replace();
this.$route.reload();
this.$rootScope.appEvent(AppEvents.alertSuccess, ['Dashboard restored', 'Restored from version ' + version]);
})
.catch(() => {
this.mode = 'list';
this.loading = false;
});
return promiseToDigest(this.$scope)(
this.historySrv
.restoreDashboard(this.dashboard, version)
.then((response: any) => {
this.$location.url(locationUtil.stripBaseFromUrl(response.url)).replace();
this.$route.reload();
this.$rootScope.appEvent(AppEvents.alertSuccess, ['Dashboard restored', 'Restored from version ' + version]);
})
.catch(() => {
this.mode = 'list';
this.loading = false;
})
);
}
}

View File

@@ -1,27 +1,41 @@
import { versions, restore } from './__mocks__/history';
import { HistorySrv } from './HistorySrv';
import { DashboardModel } from '../../state/DashboardModel';
const getMock = jest.fn().mockResolvedValue({});
const postMock = jest.fn().mockResolvedValue({});
jest.mock('app/core/store');
jest.mock('@grafana/runtime', () => {
const original = jest.requireActual('@grafana/runtime');
return {
...original,
getBackendSrv: () => ({
post: postMock,
get: getMock,
}),
};
});
describe('historySrv', () => {
const versionsResponse = versions();
const restoreResponse = restore;
const backendSrv: any = {
get: jest.fn(() => Promise.resolve({})),
post: jest.fn(() => Promise.resolve({})),
};
let historySrv = new HistorySrv(backendSrv);
let historySrv = new HistorySrv();
const dash = new DashboardModel({ id: 1 });
const emptyDash = new DashboardModel({});
const historyListOpts = { limit: 10, start: 0 };
beforeEach(() => {
jest.clearAllMocks();
});
describe('getHistoryList', () => {
it('should return a versions array for the given dashboard id', () => {
backendSrv.get = jest.fn(() => Promise.resolve(versionsResponse));
historySrv = new HistorySrv(backendSrv);
getMock.mockImplementation(() => Promise.resolve(versionsResponse));
historySrv = new HistorySrv();
return historySrv.getHistoryList(dash, historyListOpts).then((versions: any) => {
expect(versions).toEqual(versionsResponse);
@@ -44,15 +58,15 @@ describe('historySrv', () => {
describe('restoreDashboard', () => {
it('should return a success response given valid parameters', () => {
const version = 6;
backendSrv.post = jest.fn(() => Promise.resolve(restoreResponse(version)));
historySrv = new HistorySrv(backendSrv);
postMock.mockImplementation(() => Promise.resolve(restoreResponse(version)));
historySrv = new HistorySrv();
return historySrv.restoreDashboard(dash, version).then((response: any) => {
expect(response).toEqual(restoreResponse(version));
});
});
it('should return an empty object when not given an id', async () => {
historySrv = new HistorySrv(backendSrv);
historySrv = new HistorySrv();
const rsp = await historySrv.restoreDashboard(emptyDash, 6);
expect(rsp).toEqual({});
});

View File

@@ -1,7 +1,7 @@
import _ from 'lodash';
import coreModule from 'app/core/core_module';
import { DashboardModel } from '../../state/DashboardModel';
import { BackendSrv } from 'app/core/services/backend_srv';
import { getBackendSrv } from '@grafana/runtime';
export interface HistoryListOpts {
limit: number;
@@ -32,23 +32,20 @@ export interface DiffTarget {
}
export class HistorySrv {
/** @ngInject */
constructor(private backendSrv: BackendSrv) {}
getHistoryList(dashboard: DashboardModel, options: HistoryListOpts) {
const id = dashboard && dashboard.id ? dashboard.id : void 0;
return id ? this.backendSrv.get(`api/dashboards/id/${id}/versions`, options) : Promise.resolve([]);
return id ? getBackendSrv().get(`api/dashboards/id/${id}/versions`, options) : Promise.resolve([]);
}
calculateDiff(options: CalculateDiffOptions) {
return this.backendSrv.post('api/dashboards/calculate-diff', options);
return getBackendSrv().post('api/dashboards/calculate-diff', options);
}
restoreDashboard(dashboard: DashboardModel, version: number) {
const id = dashboard && dashboard.id ? dashboard.id : void 0;
const url = `api/dashboards/id/${id}/restore`;
return id && _.isNumber(version) ? this.backendSrv.post(url, { version }) : Promise.resolve({});
return id && _.isNumber(version) ? getBackendSrv().post(url, { version }) : Promise.resolve({});
}
}