Chore/Tech debt: Remove (most) instances of $q angular service use (#20668)

* Chore/Tech debt: Remove (most) instances of $q angular service use
Removes instances where the angular $q service is used and replaces
it with native Promises.
This commit is contained in:
kay delaney
2019-12-05 09:04:03 +00:00
committed by GitHub
parent 62f0aca3e6
commit 880fbcb09a
58 changed files with 320 additions and 467 deletions

View File

@@ -1,6 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import coreModule from '../../core_module'; import coreModule from '../../core_module';
import { ISCEService, IQService } from 'angular'; import { ISCEService } from 'angular';
function typeaheadMatcher(this: any, item: string) { function typeaheadMatcher(this: any, item: string) {
let str = this.query; let str = this.query;
@@ -38,13 +38,7 @@ export class FormDropdownCtrl {
debounce: number; debounce: number;
/** @ngInject */ /** @ngInject */
constructor( constructor(private $scope: any, $element: JQLite, private $sce: ISCEService, private templateSrv: any) {
private $scope: any,
$element: JQLite,
private $sce: ISCEService,
private templateSrv: any,
private $q: IQService
) {
this.inputElement = $element.find('input').first(); this.inputElement = $element.find('input').first();
this.linkElement = $element.find('a').first(); this.linkElement = $element.find('a').first();
this.linkMode = true; this.linkMode = true;
@@ -108,10 +102,7 @@ export class FormDropdownCtrl {
getOptionsInternal(query: string) { getOptionsInternal(query: string) {
const result = this.getOptions({ $query: query }); const result = this.getOptions({ $query: query });
if (this.isPromiseLike(result)) { return Promise.resolve(result);
return result;
}
return this.$q.when(result);
} }
isPromiseLike(obj: any) { isPromiseLike(obj: any) {

View File

@@ -186,8 +186,7 @@ export function metricSegment($compile: any, $sce: any, templateSrv: TemplateSrv
}; };
} }
/** @ngInject */ export function metricSegmentModel(uiSegmentSrv: any) {
export function metricSegmentModel(uiSegmentSrv: any, $q: any) {
return { return {
template: template:
'<metric-segment segment="segment" get-options="getOptionsInternal()" on-change="onSegmentChange()"></metric-segment>', '<metric-segment segment="segment" get-options="getOptionsInternal()" on-change="onSegmentChange()"></metric-segment>',
@@ -217,7 +216,7 @@ export function metricSegmentModel(uiSegmentSrv: any, $q: any) {
$scope.getOptionsInternal = () => { $scope.getOptionsInternal = () => {
if ($scope.options) { if ($scope.options) {
cachedOptions = $scope.options; cachedOptions = $scope.options;
return $q.when( return Promise.resolve(
_.map($scope.options, option => { _.map($scope.options, option => {
return { value: option.text }; return { value: option.text };
}) })

View File

@@ -28,7 +28,7 @@ export class ValueSelectDropdownCtrl {
debouncedQueryChanged: Function; debouncedQueryChanged: Function;
/** @ngInject */ /** @ngInject */
constructor(private $q: any, private $scope: IScope) { constructor(private $scope: IScope) {
this.queryHasSearchFilter = this.variable ? containsSearchFilter(this.variable.query) : false; this.queryHasSearchFilter = this.variable ? containsSearchFilter(this.variable.query) : false;
this.debouncedQueryChanged = debounce(this.queryChanged.bind(this), 200); this.debouncedQueryChanged = debounce(this.queryChanged.bind(this), 200);
} }
@@ -114,7 +114,7 @@ export class ValueSelectDropdownCtrl {
if (!tag.values) { if (!tag.values) {
tagValuesPromise = this.variable.getValuesForTag(tag.text); tagValuesPromise = this.variable.getValuesForTag(tag.text);
} else { } else {
tagValuesPromise = this.$q.when(tag.values); tagValuesPromise = Promise.resolve(tag.values);
} }
return tagValuesPromise.then((values: any) => { return tagValuesPromise.then((values: any) => {

View File

@@ -1,6 +1,4 @@
import _ from 'lodash'; import _ from 'lodash';
// @ts-ignore
import { IQService } from 'angular';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import impressionSrv from 'app/core/services/impression_srv'; import impressionSrv from 'app/core/services/impression_srv';
@@ -19,7 +17,7 @@ export class SearchSrv {
starredIsOpen: boolean; starredIsOpen: boolean;
/** @ngInject */ /** @ngInject */
constructor(private backendSrv: BackendSrv, private $q: IQService) { constructor(private backendSrv: BackendSrv) {
this.recentIsOpen = store.getBool('search.sections.recent', true); this.recentIsOpen = store.getBool('search.sections.recent', true);
this.starredIsOpen = store.getBool('search.sections.starred', true); this.starredIsOpen = store.getBool('search.sections.starred', true);
} }
@@ -123,7 +121,7 @@ export class SearchSrv {
}) })
); );
return this.$q.all(promises).then(() => { return Promise.all(promises).then(() => {
return _.sortBy(_.values(sections), 'score'); return _.sortBy(_.values(sections), 'score');
}); });
} }

View File

@@ -1,6 +1,3 @@
// @ts-ignore
import { IQService } from 'angular';
import { SearchSrv } from 'app/core/services/search_srv'; import { SearchSrv } from 'app/core/services/search_srv';
import { BackendSrvMock } from 'test/mocks/backend_srv'; import { BackendSrvMock } from 'test/mocks/backend_srv';
import impressionSrv from 'app/core/services/impression_srv'; import impressionSrv from 'app/core/services/impression_srv';
@@ -26,7 +23,7 @@ describe('SearchSrv', () => {
beforeEach(() => { beforeEach(() => {
backendSrvMock = new BackendSrvMock(); backendSrvMock = new BackendSrvMock();
searchSrv = new SearchSrv(backendSrvMock as BackendSrv, (Promise as any) as IQService); searchSrv = new SearchSrv(backendSrvMock as BackendSrv);
contextSrv.isSignedIn = true; contextSrv.isSignedIn = true;
impressionSrv.getDashboardOpened = jest.fn().mockReturnValue([]); impressionSrv.getDashboardOpened = jest.fn().mockReturnValue([]);

View File

@@ -1,7 +1,5 @@
import 'app/core/directives/value_select_dropdown'; import 'app/core/directives/value_select_dropdown';
import { ValueSelectDropdownCtrl } from '../directives/value_select_dropdown'; import { ValueSelectDropdownCtrl } from '../directives/value_select_dropdown';
// @ts-ignore
import q from 'q';
import { IScope } from 'angular'; import { IScope } from 'angular';
describe('SelectDropdownCtrl', () => { describe('SelectDropdownCtrl', () => {
@@ -13,7 +11,7 @@ describe('SelectDropdownCtrl', () => {
describe('Given simple variable', () => { describe('Given simple variable', () => {
beforeEach(() => { beforeEach(() => {
ctrl = new ValueSelectDropdownCtrl(q, $scope); ctrl = new ValueSelectDropdownCtrl($scope);
ctrl.variable = { ctrl.variable = {
current: { text: 'hej', value: 'hej' }, current: { text: 'hej', value: 'hej' },
getValuesForTag: (key: string) => { getValuesForTag: (key: string) => {
@@ -30,7 +28,7 @@ describe('SelectDropdownCtrl', () => {
describe('Given variable with tags and dropdown is opened', () => { describe('Given variable with tags and dropdown is opened', () => {
beforeEach(() => { beforeEach(() => {
ctrl = new ValueSelectDropdownCtrl(q, $scope); ctrl = new ValueSelectDropdownCtrl($scope);
ctrl.variable = { ctrl.variable = {
current: { text: 'server-1', value: 'server-1' }, current: { text: 'server-1', value: 'server-1' },
options: [ options: [
@@ -133,7 +131,7 @@ describe('SelectDropdownCtrl', () => {
describe('Given variable with selected tags', () => { describe('Given variable with selected tags', () => {
beforeEach(() => { beforeEach(() => {
ctrl = new ValueSelectDropdownCtrl(q, $scope); ctrl = new ValueSelectDropdownCtrl($scope);
ctrl.variable = { ctrl.variable = {
current: { current: {
text: 'server-1', text: 'server-1',
@@ -165,7 +163,7 @@ describe('queryChanged', () => {
describe('when called and variable query contains search filter', () => { describe('when called and variable query contains search filter', () => {
it('then it should use lazy loading', async () => { it('then it should use lazy loading', async () => {
const $scope = {} as IScope; const $scope = {} as IScope;
const ctrl = new ValueSelectDropdownCtrl(q, $scope); const ctrl = new ValueSelectDropdownCtrl($scope);
const options = [ const options = [
{ text: 'server-1', value: 'server-1' }, { text: 'server-1', value: 'server-1' },
{ text: 'server-2', value: 'server-2' }, { text: 'server-2', value: 'server-2' },
@@ -190,7 +188,7 @@ describe('queryChanged', () => {
describe('when called and variable query does not contain search filter', () => { describe('when called and variable query does not contain search filter', () => {
it('then it should not use lazy loading', async () => { it('then it should not use lazy loading', async () => {
const $scope = {} as IScope; const $scope = {} as IScope;
const ctrl = new ValueSelectDropdownCtrl(q, $scope); const ctrl = new ValueSelectDropdownCtrl($scope);
ctrl.lazyLoadOptions = jest.fn().mockResolvedValue([]); ctrl.lazyLoadOptions = jest.fn().mockResolvedValue([]);
ctrl.updateUIBoundOptions = jest.fn(); ctrl.updateUIBoundOptions = jest.fn();
ctrl.search = { ctrl.search = {
@@ -210,7 +208,7 @@ describe('lazyLoadOptions', () => {
describe('when called with a query', () => { describe('when called with a query', () => {
it('then the variables updateOptions should be called with the query', async () => { it('then the variables updateOptions should be called with the query', async () => {
const $scope = {} as IScope; const $scope = {} as IScope;
const ctrl = new ValueSelectDropdownCtrl(q, $scope); const ctrl = new ValueSelectDropdownCtrl($scope);
ctrl.variable = { ctrl.variable = {
updateOptions: jest.fn(), updateOptions: jest.fn(),
options: [ options: [
@@ -244,7 +242,7 @@ describe('updateUIBoundOptions', () => {
for (let index = 0; index < 1001; index++) { for (let index = 0; index < 1001; index++) {
options.push({ text: `server-${index}`, value: `server-${index}` }); options.push({ text: `server-${index}`, value: `server-${index}` });
} }
ctrl = new ValueSelectDropdownCtrl(q, $scope); ctrl = new ValueSelectDropdownCtrl($scope);
ctrl.highlightIndex = 0; ctrl.highlightIndex = 0;
ctrl.options = []; ctrl.options = [];
ctrl.search = { ctrl.search = {

View File

@@ -38,7 +38,6 @@ export class AlertTabCtrl {
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private dashboardSrv: DashboardSrv, private dashboardSrv: DashboardSrv,
private uiSegmentSrv: any, private uiSegmentSrv: any,
private $q: any,
private datasourceSrv: DatasourceSrv private datasourceSrv: DatasourceSrv
) { ) {
this.panelCtrl = $scope.ctrl; this.panelCtrl = $scope.ctrl;
@@ -121,7 +120,7 @@ export class AlertTabCtrl {
} }
getNotifications() { getNotifications() {
return this.$q.when( return Promise.resolve(
this.notifications.map((item: any) => { this.notifications.map((item: any) => {
return this.uiSegmentSrv.newSegment(item.name); return this.uiSegmentSrv.newSegment(item.name);
}) })
@@ -305,7 +304,7 @@ export class AlertTabCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([]); return Promise.resolve([]);
} }
case 'part-param-changed': { case 'part-param-changed': {
this.validateModel(); this.validateModel();
@@ -315,9 +314,14 @@ export class AlertTabCtrl {
return this.uiSegmentSrv.newSegment({ value: target.refId }); return this.uiSegmentSrv.newSegment({ value: target.refId });
}); });
return this.$q.when(result); return Promise.resolve(result);
}
default: {
return Promise.resolve();
} }
} }
return Promise.resolve();
} }
handleReducerPartEvent(conditionModel: any, evt: any) { handleReducerPartEvent(conditionModel: any, evt: any) {
@@ -334,9 +338,11 @@ export class AlertTabCtrl {
result.push(type); result.push(type);
} }
} }
return this.$q.when(result); return Promise.resolve(result);
} }
} }
return Promise.resolve();
} }
addCondition(type: string) { addCondition(type: string) {

View File

@@ -1,5 +1,5 @@
// Libaries // Libaries
import angular, { IQService } from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
// Components // Components
@@ -25,7 +25,6 @@ export class AnnotationsSrv {
/** @ngInject */ /** @ngInject */
constructor( constructor(
private $rootScope: GrafanaRootScope, private $rootScope: GrafanaRootScope,
private $q: IQService,
private datasourceSrv: DatasourceSrv, private datasourceSrv: DatasourceSrv,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
@@ -45,8 +44,7 @@ export class AnnotationsSrv {
} }
getAnnotations(options: { dashboard: DashboardModel; panel: PanelModel; range: TimeRange }) { getAnnotations(options: { dashboard: DashboardModel; panel: PanelModel; range: TimeRange }) {
return this.$q return Promise.all([this.getGlobalAnnotations(options), this.getAlertStates(options)])
.all([this.getGlobalAnnotations(options), this.getAlertStates(options)])
.then(results => { .then(results => {
// combine the annotations and flatten results // combine the annotations and flatten results
let annotations: AnnotationEvent[] = _.flattenDeep(results[0]); let annotations: AnnotationEvent[] = _.flattenDeep(results[0]);
@@ -82,16 +80,16 @@ export class AnnotationsSrv {
getAlertStates(options: any) { getAlertStates(options: any) {
if (!options.dashboard.id) { if (!options.dashboard.id) {
return this.$q.when([]); return Promise.resolve([]);
} }
// ignore if no alerts // ignore if no alerts
if (options.panel && !options.panel.alert) { if (options.panel && !options.panel.alert) {
return this.$q.when([]); return Promise.resolve([]);
} }
if (options.range.raw.to !== 'now') { if (options.range.raw.to !== 'now') {
return this.$q.when([]); return Promise.resolve([]);
} }
if (this.alertStatesPromise) { if (this.alertStatesPromise) {
@@ -146,8 +144,8 @@ export class AnnotationsSrv {
}) })
); );
} }
this.datasourcePromises = this.$q.all(dsPromises); this.datasourcePromises = Promise.all(dsPromises);
this.globalAnnotationsPromise = this.$q.all(promises); this.globalAnnotationsPromise = Promise.all(promises);
return this.globalAnnotationsPromise; return this.globalAnnotationsPromise;
} }

View File

@@ -5,7 +5,7 @@ describe('AnnotationsSrv', () => {
onAppEvent: jest.fn(), onAppEvent: jest.fn(),
}; };
const annotationsSrv = new AnnotationsSrv($rootScope, null, null, null, null); const annotationsSrv = new AnnotationsSrv($rootScope, null, null, null);
describe('When translating the query result', () => { describe('When translating the query result', () => {
const annotationSource = { const annotationSource = {

View File

@@ -1,5 +1,5 @@
import _ from 'lodash'; import _ from 'lodash';
import angular, { IQService } from 'angular'; import angular from 'angular';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import { DashboardModel } from 'app/features/dashboard/state'; import { DashboardModel } from 'app/features/dashboard/state';
import DatasourceSrv from 'app/features/plugins/datasource_srv'; import DatasourceSrv from 'app/features/plugins/datasource_srv';
@@ -16,7 +16,6 @@ export class AdHocFiltersCtrl {
constructor( constructor(
private uiSegmentSrv: any, private uiSegmentSrv: any,
private datasourceSrv: DatasourceSrv, private datasourceSrv: DatasourceSrv,
private $q: IQService,
private variableSrv: VariableSrv, private variableSrv: VariableSrv,
$scope: any $scope: any
) { ) {
@@ -51,11 +50,11 @@ export class AdHocFiltersCtrl {
getOptions(segment: { type: string }, index: number) { getOptions(segment: { type: string }, index: number) {
if (segment.type === 'operator') { if (segment.type === 'operator') {
return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '>', '=~', '!~'])); return Promise.resolve(this.uiSegmentSrv.newOperators(['=', '!=', '<', '>', '=~', '!~']));
} }
if (segment.type === 'condition') { if (segment.type === 'condition') {
return this.$q.when([this.uiSegmentSrv.newSegment('AND')]); return Promise.resolve([this.uiSegmentSrv.newSegment('AND')]);
} }
return this.datasourceSrv.get(this.variable.datasource).then(ds => { return this.datasourceSrv.get(this.variable.datasource).then(ds => {

View File

@@ -1,4 +1,4 @@
import angular, { IQService } from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import { iconMap } from './DashLinksEditorCtrl'; import { iconMap } from './DashLinksEditorCtrl';
import { LinkSrv } from 'app/features/panel/panellinks/link_srv'; import { LinkSrv } from 'app/features/panel/panellinks/link_srv';
@@ -97,7 +97,6 @@ export class DashLinksContainerCtrl {
constructor( constructor(
$scope: any, $scope: any,
$rootScope: GrafanaRootScope, $rootScope: GrafanaRootScope,
$q: IQService,
backendSrv: BackendSrv, backendSrv: BackendSrv,
dashboardSrv: DashboardSrv, dashboardSrv: DashboardSrv,
linkSrv: LinkSrv linkSrv: LinkSrv
@@ -108,11 +107,11 @@ export class DashLinksContainerCtrl {
if (linkDef.type === 'dashboards') { if (linkDef.type === 'dashboards') {
if (!linkDef.tags) { if (!linkDef.tags) {
console.log('Dashboard link missing tag'); console.log('Dashboard link missing tag');
return $q.when([]); return Promise.resolve([]);
} }
if (linkDef.asDropdown) { if (linkDef.asDropdown) {
return $q.when([ return Promise.resolve([
{ {
title: linkDef.title, title: linkDef.title,
tags: linkDef.tags, tags: linkDef.tags,
@@ -129,7 +128,7 @@ export class DashLinksContainerCtrl {
} }
if (linkDef.type === 'link') { if (linkDef.type === 'link') {
return $q.when([ return Promise.resolve([
{ {
url: linkDef.url, url: linkDef.url,
title: linkDef.title, title: linkDef.title,
@@ -143,13 +142,13 @@ export class DashLinksContainerCtrl {
]); ]);
} }
return $q.when([]); return Promise.resolve([]);
} }
function updateDashLinks() { function updateDashLinks() {
const promises = _.map($scope.links, buildLinks); const promises = _.map($scope.links, buildLinks);
$q.all(promises).then(results => { Promise.all(promises).then(results => {
$scope.generatedLinks = _.flatten(results); $scope.generatedLinks = _.flatten(results);
}); });
} }

View File

@@ -1,8 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import { HistoryListCtrl } from './HistoryListCtrl'; import { HistoryListCtrl } from './HistoryListCtrl';
import { versions, compare, restore } from './__mocks__/history'; import { versions, compare, restore } from './__mocks__/history';
// @ts-ignore
import $q from 'q';
import { CoreEvents } from 'app/types'; import { CoreEvents } from 'app/types';
describe('HistoryListCtrl', () => { describe('HistoryListCtrl', () => {
@@ -18,7 +16,7 @@ describe('HistoryListCtrl', () => {
beforeEach(() => { beforeEach(() => {
historySrv = { historySrv = {
calculateDiff: jest.fn(), calculateDiff: jest.fn(),
restoreDashboard: jest.fn(() => $q.when({})), restoreDashboard: jest.fn(() => Promise.resolve({})),
}; };
$rootScope = { $rootScope = {
appEvent: jest.fn(), appEvent: jest.fn(),
@@ -27,13 +25,10 @@ describe('HistoryListCtrl', () => {
}); });
describe('when the history list component is loaded', () => { describe('when the history list component is loaded', () => {
let deferred: any;
beforeEach(() => { beforeEach(() => {
deferred = $q.defer({}); historySrv.getHistoryList = jest.fn(() => Promise.resolve({}));
historySrv.getHistoryList = jest.fn(() => deferred.promise);
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, $q, historySrv, {}); historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl.dashboard = { historyListCtrl.dashboard = {
id: 2, id: 2,
@@ -48,7 +43,7 @@ describe('HistoryListCtrl', () => {
describe('and the history list is successfully fetched', () => { describe('and the history list is successfully fetched', () => {
beforeEach(async () => { beforeEach(async () => {
deferred.resolve(versionsResponse); historySrv.getHistoryList = jest.fn(() => Promise.resolve(versionsResponse));
await historyListCtrl.getLog(); await historyListCtrl.getLog();
}); });
@@ -87,13 +82,9 @@ describe('HistoryListCtrl', () => {
describe('and fetching the history list fails', () => { describe('and fetching the history list fails', () => {
beforeEach(async () => { beforeEach(async () => {
deferred = $q.defer(); historySrv.getHistoryList = jest.fn(() => Promise.reject(new Error('HistoryListError')));
historySrv.getHistoryList = jest.fn(() => deferred.promise); historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, $q, historySrv, {});
deferred.reject(new Error('HistoryListError'));
await historyListCtrl.getLog(); await historyListCtrl.getLog();
}); });
@@ -132,14 +123,11 @@ describe('HistoryListCtrl', () => {
}); });
describe('when the user wants to compare two revisions', () => { describe('when the user wants to compare two revisions', () => {
let deferred: any;
beforeEach(async () => { beforeEach(async () => {
deferred = $q.defer({}); historySrv.getHistoryList = jest.fn(() => Promise.resolve(versionsResponse));
historySrv.getHistoryList = jest.fn(() => $q.when(versionsResponse)); historySrv.calculateDiff = jest.fn(() => Promise.resolve({}));
historySrv.calculateDiff = jest.fn(() => deferred.promise);
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, $q, historySrv, {}); historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl.dashboard = { historyListCtrl.dashboard = {
id: 2, id: 2,
@@ -147,7 +135,7 @@ describe('HistoryListCtrl', () => {
formatDate: jest.fn(() => 'date'), formatDate: jest.fn(() => 'date'),
}; };
deferred.resolve(versionsResponse); historySrv.calculateDiff = jest.fn(() => Promise.resolve(versionsResponse));
await historyListCtrl.getLog(); await historyListCtrl.getLog();
}); });
@@ -173,9 +161,7 @@ describe('HistoryListCtrl', () => {
describe('and the basic diff is successfully fetched', () => { describe('and the basic diff is successfully fetched', () => {
beforeEach(async () => { beforeEach(async () => {
deferred = $q.defer({}); historySrv.calculateDiff = jest.fn(() => Promise.resolve(compare('basic')));
historySrv.calculateDiff = jest.fn(() => deferred.promise);
deferred.resolve(compare('basic'));
historyListCtrl.revisions[1].checked = true; historyListCtrl.revisions[1].checked = true;
historyListCtrl.revisions[3].checked = true; historyListCtrl.revisions[3].checked = true;
await historyListCtrl.getDiff('basic'); await historyListCtrl.getDiff('basic');
@@ -199,9 +185,7 @@ describe('HistoryListCtrl', () => {
describe('and the json diff is successfully fetched', () => { describe('and the json diff is successfully fetched', () => {
beforeEach(async () => { beforeEach(async () => {
deferred = $q.defer({}); historySrv.calculateDiff = jest.fn(() => Promise.resolve(compare('json')));
historySrv.calculateDiff = jest.fn(() => deferred.promise);
deferred.resolve(compare('json'));
historyListCtrl.revisions[1].checked = true; historyListCtrl.revisions[1].checked = true;
historyListCtrl.revisions[3].checked = true; historyListCtrl.revisions[3].checked = true;
await historyListCtrl.getDiff('json'); await historyListCtrl.getDiff('json');
@@ -225,7 +209,7 @@ describe('HistoryListCtrl', () => {
describe('and diffs have already been fetched', () => { describe('and diffs have already been fetched', () => {
beforeEach(async () => { beforeEach(async () => {
deferred.resolve(compare('basic')); historySrv.calculateDiff = jest.fn(() => Promise.resolve(compare('basic')));
historyListCtrl.revisions[3].checked = true; historyListCtrl.revisions[3].checked = true;
historyListCtrl.revisions[1].checked = true; historyListCtrl.revisions[1].checked = true;
@@ -246,12 +230,10 @@ describe('HistoryListCtrl', () => {
describe('and fetching the diff fails', () => { describe('and fetching the diff fails', () => {
beforeEach(async () => { beforeEach(async () => {
deferred = $q.defer({}); historySrv.calculateDiff = jest.fn(() => Promise.reject());
historySrv.calculateDiff = jest.fn(() => deferred.promise);
historyListCtrl.revisions[3].checked = true; historyListCtrl.revisions[3].checked = true;
historyListCtrl.revisions[1].checked = true; historyListCtrl.revisions[1].checked = true;
deferred.reject();
await historyListCtrl.getDiff('basic'); await historyListCtrl.getDiff('basic');
}); });
@@ -274,20 +256,17 @@ describe('HistoryListCtrl', () => {
}); });
describe('when the user wants to restore a revision', () => { describe('when the user wants to restore a revision', () => {
let deferred: any;
beforeEach(async () => { beforeEach(async () => {
deferred = $q.defer(); historySrv.getHistoryList = jest.fn(() => Promise.resolve(versionsResponse));
historySrv.getHistoryList = jest.fn(() => $q.when(versionsResponse)); historySrv.restoreDashboard = jest.fn(() => Promise.resolve());
historySrv.restoreDashboard = jest.fn(() => deferred.promise);
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, $q, historySrv, {}); historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl.dashboard = { historyListCtrl.dashboard = {
id: 1, id: 1,
}; };
historyListCtrl.restore(); historyListCtrl.restore();
deferred.resolve(versionsResponse); historySrv.restoreDashboard = jest.fn(() => Promise.resolve(versionsResponse));
await historyListCtrl.getLog(); await historyListCtrl.getLog();
}); });
@@ -298,11 +277,10 @@ describe('HistoryListCtrl', () => {
describe('and restore fails to fetch', () => { describe('and restore fails to fetch', () => {
beforeEach(async () => { beforeEach(async () => {
deferred = $q.defer(); historySrv.getHistoryList = jest.fn(() => Promise.resolve(versionsResponse));
historySrv.getHistoryList = jest.fn(() => $q.when(versionsResponse)); historySrv.restoreDashboard = jest.fn(() => Promise.resolve());
historySrv.restoreDashboard = jest.fn(() => deferred.promise); historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, historySrv, {});
historyListCtrl = new HistoryListCtrl({}, $rootScope, {} as any, $q, historySrv, {}); historySrv.restoreDashboard = jest.fn(() => Promise.reject(new Error('RestoreError')));
deferred.reject(new Error('RestoreError'));
historyListCtrl.restoreConfirm(RESTORE_ID); historyListCtrl.restoreConfirm(RESTORE_ID);
await historyListCtrl.getLog(); await historyListCtrl.getLog();
}); });

View File

@@ -1,5 +1,5 @@
import _ from 'lodash'; import _ from 'lodash';
import angular, { ILocationService, IQService } from 'angular'; import angular, { ILocationService } from 'angular';
import locationUtil from 'app/core/utils/location_util'; import locationUtil from 'app/core/utils/location_util';
import { DashboardModel } from '../../state/DashboardModel'; import { DashboardModel } from '../../state/DashboardModel';
@@ -29,7 +29,6 @@ export class HistoryListCtrl {
private $route: any, private $route: any,
private $rootScope: GrafanaRootScope, private $rootScope: GrafanaRootScope,
private $location: ILocationService, private $location: ILocationService,
private $q: IQService,
private historySrv: HistorySrv, private historySrv: HistorySrv,
public $scope: any public $scope: any
) { ) {
@@ -81,15 +80,13 @@ export class HistoryListCtrl {
return then.from(now); return then.from(now);
} }
getDiff(diff: string) { getDiff(diff: 'basic' | 'json') {
this.diff = diff; this.diff = diff;
this.mode = 'compare'; this.mode = 'compare';
// have it already been fetched? // has it already been fetched?
// @ts-ignore if (this.delta[diff]) {
if (this.delta[this.diff]) { return Promise.resolve(this.delta[diff]);
// @ts-ignore
return this.$q.when(this.delta[this.diff]);
} }
const selected = _.filter(this.revisions, { checked: true }); const selected = _.filter(this.revisions, { checked: true });

View File

@@ -1,5 +1,5 @@
/* tslint:disable:import-blacklist */ /* tslint:disable:import-blacklist */
import angular, { IQService } from 'angular'; import angular from 'angular';
import moment from 'moment'; import moment from 'moment';
import _ from 'lodash'; import _ from 'lodash';
import $ from 'jquery'; import $ from 'jquery';
@@ -19,7 +19,6 @@ export class DashboardLoaderSrv {
private dashboardSrv: DashboardSrv, private dashboardSrv: DashboardSrv,
private datasourceSrv: DatasourceSrv, private datasourceSrv: DatasourceSrv,
private $http: any, private $http: any,
private $q: IQService,
private $timeout: any, private $timeout: any,
contextSrv: any, contextSrv: any,
private $routeParams: any, private $routeParams: any,
@@ -108,7 +107,6 @@ export class DashboardLoaderSrv {
const services = { const services = {
dashboardSrv: this.dashboardSrv, dashboardSrv: this.dashboardSrv,
datasourceSrv: this.datasourceSrv, datasourceSrv: this.datasourceSrv,
$q: this.$q,
}; };
/*jshint -W054 */ /*jshint -W054 */
@@ -129,13 +127,13 @@ export class DashboardLoaderSrv {
// Handle async dashboard scripts // Handle async dashboard scripts
if (_.isFunction(scriptResult)) { if (_.isFunction(scriptResult)) {
const deferred = this.$q.defer(); return new Promise(resolve => {
scriptResult((dashboard: any) => { scriptResult((dashboard: any) => {
this.$timeout(() => { this.$timeout(() => {
deferred.resolve({ data: dashboard }); resolve({ data: dashboard });
});
}); });
}); });
return deferred.promise;
} }
return { data: scriptResult }; return { data: scriptResult };

View File

@@ -1,4 +1,4 @@
import angular, { IQService, ILocationService } from 'angular'; import angular, { ILocationService } from 'angular';
import { ChangeTracker } from './ChangeTracker'; import { ChangeTracker } from './ChangeTracker';
import { ContextSrv } from 'app/core/services/context_srv'; import { ContextSrv } from 'app/core/services/context_srv';
import { DashboardSrv } from './DashboardSrv'; import { DashboardSrv } from './DashboardSrv';
@@ -8,7 +8,6 @@ import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
export function unsavedChangesSrv( export function unsavedChangesSrv(
this: any, this: any,
$rootScope: GrafanaRootScope, $rootScope: GrafanaRootScope,
$q: IQService,
$location: ILocationService, $location: ILocationService,
$timeout: any, $timeout: any,
contextSrv: ContextSrv, contextSrv: ContextSrv,

View File

@@ -1,5 +1,4 @@
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import { IQService } from 'angular';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
const hitTypes = { const hitTypes = {
@@ -10,8 +9,7 @@ const hitTypes = {
export class ValidationSrv { export class ValidationSrv {
rootName = 'general'; rootName = 'general';
/** @ngInject */ constructor(private backendSrv: BackendSrv) {}
constructor(private $q: IQService, private backendSrv: BackendSrv) {}
validateNewDashboardName(folderId: any, name: string) { validateNewDashboardName(folderId: any, name: string) {
return this.validate(folderId, name, 'A dashboard in this folder with the same name already exists'); return this.validate(folderId, name, 'A dashboard in this folder with the same name already exists');
@@ -26,26 +24,24 @@ export class ValidationSrv {
const nameLowerCased = name.toLowerCase(); const nameLowerCased = name.toLowerCase();
if (name.length === 0) { if (name.length === 0) {
return this.$q.reject({ return Promise.reject({
type: 'REQUIRED', type: 'REQUIRED',
message: 'Name is required', message: 'Name is required',
}); });
} }
if (folderId === 0 && nameLowerCased === this.rootName) { if (folderId === 0 && nameLowerCased === this.rootName) {
return this.$q.reject({ return Promise.reject({
type: 'EXISTING', type: 'EXISTING',
message: 'This is a reserved name and cannot be used for a folder.', message: 'This is a reserved name and cannot be used for a folder.',
}); });
} }
const deferred = this.$q.defer();
const promises = []; const promises = [];
promises.push(this.backendSrv.search({ type: hitTypes.FOLDER, folderIds: [folderId], query: name })); promises.push(this.backendSrv.search({ type: hitTypes.FOLDER, folderIds: [folderId], query: name }));
promises.push(this.backendSrv.search({ type: hitTypes.DASHBOARD, folderIds: [folderId], query: name })); promises.push(this.backendSrv.search({ type: hitTypes.DASHBOARD, folderIds: [folderId], query: name }));
this.$q.all(promises).then(res => { return Promise.all(promises).then(res => {
let hits: any[] = []; let hits: any[] = [];
if (res.length > 0 && res[0].length > 0) { if (res.length > 0 && res[0].length > 0) {
@@ -58,18 +54,15 @@ export class ValidationSrv {
for (const hit of hits) { for (const hit of hits) {
if (nameLowerCased === hit.title.toLowerCase()) { if (nameLowerCased === hit.title.toLowerCase()) {
deferred.reject({ throw {
type: 'EXISTING', type: 'EXISTING',
message: existingErrorMessage, message: existingErrorMessage,
}); };
break;
} }
} }
deferred.resolve(); return;
}); });
return deferred.promise;
} }
} }

View File

@@ -25,7 +25,6 @@ import { CoreEvents } from 'app/types';
class MetricsPanelCtrl extends PanelCtrl { class MetricsPanelCtrl extends PanelCtrl {
scope: any; scope: any;
datasource: DataSourceApi; datasource: DataSourceApi;
$q: any;
$timeout: any; $timeout: any;
contextSrv: ContextSrv; contextSrv: ContextSrv;
datasourceSrv: any; datasourceSrv: any;
@@ -44,7 +43,6 @@ class MetricsPanelCtrl extends PanelCtrl {
constructor($scope: any, $injector: any) { constructor($scope: any, $injector: any) {
super($scope, $injector); super($scope, $injector);
this.$q = $injector.get('$q');
this.contextSrv = $injector.get('contextSrv'); this.contextSrv = $injector.get('contextSrv');
this.datasourceSrv = $injector.get('datasourceSrv'); this.datasourceSrv = $injector.get('datasourceSrv');
this.timeSrv = $injector.get('timeSrv'); this.timeSrv = $injector.get('timeSrv');

View File

@@ -21,7 +21,6 @@ export class DatasourceSrv implements DataSourceService {
/** @ngInject */ /** @ngInject */
constructor( constructor(
private $q: any,
private $injector: auto.IInjectorService, private $injector: auto.IInjectorService,
private $rootScope: GrafanaRootScope, private $rootScope: GrafanaRootScope,
private templateSrv: TemplateSrv private templateSrv: TemplateSrv
@@ -51,7 +50,7 @@ export class DatasourceSrv implements DataSourceService {
} }
if (this.datasources[name]) { if (this.datasources[name]) {
return this.$q.when(this.datasources[name]); return Promise.resolve(this.datasources[name]);
} }
return this.loadDatasource(name); return this.loadDatasource(name);
@@ -61,22 +60,19 @@ export class DatasourceSrv implements DataSourceService {
// Expression Datasource (not a real datasource) // Expression Datasource (not a real datasource)
if (name === expressionDatasource.name) { if (name === expressionDatasource.name) {
this.datasources[name] = expressionDatasource as any; this.datasources[name] = expressionDatasource as any;
return this.$q.when(expressionDatasource); return Promise.resolve(expressionDatasource);
} }
const dsConfig = config.datasources[name]; const dsConfig = config.datasources[name];
if (!dsConfig) { if (!dsConfig) {
return this.$q.reject({ message: `Datasource named ${name} was not found` }); return Promise.reject({ message: `Datasource named ${name} was not found` });
} }
const deferred = this.$q.defer(); return importDataSourcePlugin(dsConfig.meta)
importDataSourcePlugin(dsConfig.meta)
.then(dsPlugin => { .then(dsPlugin => {
// check if its in cache now // check if its in cache now
if (this.datasources[name]) { if (this.datasources[name]) {
deferred.resolve(this.datasources[name]); return this.datasources[name];
return;
} }
// If there is only one constructor argument it is instanceSettings // If there is only one constructor argument it is instanceSettings
@@ -92,13 +88,12 @@ export class DatasourceSrv implements DataSourceService {
// store in instance cache // store in instance cache
this.datasources[name] = instance; this.datasources[name] = instance;
deferred.resolve(instance); return instance;
}) })
.catch(err => { .catch(err => {
this.$rootScope.appEvent(AppEvents.alertError, [dsConfig.name + ' plugin failed', err.toString()]); this.$rootScope.appEvent(AppEvents.alertError, [dsConfig.name + ' plugin failed', err.toString()]);
return undefined;
}); });
return deferred.promise;
} }
getAll() { getAll() {

View File

@@ -1,4 +1,4 @@
import angular, { IQService } from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import config from 'app/core/config'; import config from 'app/core/config';
@@ -14,18 +14,17 @@ function pluginDirectiveLoader(
$compile: any, $compile: any,
datasourceSrv: DatasourceSrv, datasourceSrv: DatasourceSrv,
$rootScope: GrafanaRootScope, $rootScope: GrafanaRootScope,
$q: IQService,
$http: any, $http: any,
$templateCache: any, $templateCache: any,
$timeout: any $timeout: any
) { ) {
function getTemplate(component: { template: any; templateUrl: any }) { function getTemplate(component: { template: any; templateUrl: any }) {
if (component.template) { if (component.template) {
return $q.when(component.template); return Promise.resolve(component.template);
} }
const cached = $templateCache.get(component.templateUrl); const cached = $templateCache.get(component.templateUrl);
if (cached) { if (cached) {
return $q.when(cached); return Promise.resolve(cached);
} }
return $http.get(component.templateUrl).then((res: any) => { return $http.get(component.templateUrl).then((res: any) => {
return res.data; return res.data;
@@ -113,7 +112,7 @@ function pluginDirectiveLoader(
case 'query-ctrl': { case 'query-ctrl': {
const ds: DataSourceApi = scope.ctrl.datasource as DataSourceApi; const ds: DataSourceApi = scope.ctrl.datasource as DataSourceApi;
return $q.when({ return Promise.resolve({
baseUrl: ds.meta.baseUrl, baseUrl: ds.meta.baseUrl,
name: 'query-ctrl-' + ds.meta.id, name: 'query-ctrl-' + ds.meta.id,
bindings: { target: '=', panelCtrl: '=', datasource: '=' }, bindings: { target: '=', panelCtrl: '=', datasource: '=' },
@@ -192,7 +191,7 @@ function pluginDirectiveLoader(
return loadPanelComponentInfo(scope, attrs); return loadPanelComponentInfo(scope, attrs);
} }
default: { default: {
return $q.reject({ return Promise.reject({
message: 'Could not find component type: ' + attrs.type, message: 'Could not find component type: ' + attrs.type,
}); });
} }

View File

@@ -1,4 +1,4 @@
import angular, { IQService } from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import { getPluginSettings } from './PluginSettingsCache'; import { getPluginSettings } from './PluginSettingsCache';
@@ -14,16 +14,10 @@ export class AppPageCtrl {
navModel: any; navModel: any;
/** @ngInject */ /** @ngInject */
constructor( constructor(private $routeParams: any, private $rootScope: GrafanaRootScope, private navModelSrv: NavModelSrv) {
private $routeParams: any,
private $rootScope: GrafanaRootScope,
private navModelSrv: NavModelSrv,
private $q: IQService
) {
this.pluginId = $routeParams.pluginId; this.pluginId = $routeParams.pluginId;
this.$q Promise.resolve(getPluginSettings(this.pluginId))
.when(getPluginSettings(this.pluginId))
.then(settings => { .then(settings => {
this.initPage(settings); this.initPage(settings);
}) })

View File

@@ -17,7 +17,7 @@ const templateSrv: any = {
}; };
describe('datasource_srv', () => { describe('datasource_srv', () => {
const _datasourceSrv = new DatasourceSrv({}, {} as any, {} as any, templateSrv); const _datasourceSrv = new DatasourceSrv({} as any, {} as any, templateSrv);
describe('when loading external datasources', () => { describe('when loading external datasources', () => {
beforeEach(() => { beforeEach(() => {

View File

@@ -31,8 +31,8 @@ const setup = () => {
), ),
]); ]);
const datasource = new CloudWatchDatasource(instanceSettings, {} as any, {} as any, templateSrv as any, {} as any); const datasource = new CloudWatchDatasource(instanceSettings, {} as any, templateSrv as any, {} as any);
datasource.metricFindQuery = async param => [{ value: 'test', label: 'test' }]; datasource.metricFindQuery = async () => [{ value: 'test', label: 'test' }];
const props: Props = { const props: Props = {
query: { query: {

View File

@@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import angular, { IQService } from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import { notifyApp } from 'app/core/actions'; import { notifyApp } from 'app/core/actions';
import { createErrorNotification } from 'app/core/copy/appNotification'; import { createErrorNotification } from 'app/core/copy/appNotification';
@@ -48,7 +48,6 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery,
/** @ngInject */ /** @ngInject */
constructor( constructor(
instanceSettings: DataSourceInstanceSettings<CloudWatchJsonData>, instanceSettings: DataSourceInstanceSettings<CloudWatchJsonData>,
private $q: IQService,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
@@ -110,9 +109,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery,
// No valid targets, return the empty result to save a round trip. // No valid targets, return the empty result to save a round trip.
if (_.isEmpty(queries)) { if (_.isEmpty(queries)) {
const d = this.$q.defer(); return Promise.resolve({ data: [] });
d.resolve({ data: [] });
return d.promise;
} }
const request = { const request = {
@@ -475,7 +472,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery,
return this.standardStatistics.map((s: string) => ({ value: s, label: s, text: s })); return this.standardStatistics.map((s: string) => ({ value: s, label: s, text: s }));
} }
return this.$q.when([]); return Promise.resolve([]);
} }
annotationQuery(options: any) { annotationQuery(options: any) {

View File

@@ -1,4 +1,4 @@
import angular, { IQService } from 'angular'; import angular from 'angular';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import _ from 'lodash'; import _ from 'lodash';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
@@ -6,7 +6,7 @@ import DatasourceSrv from 'app/features/plugins/datasource_srv';
export class CloudWatchQueryParameterCtrl { export class CloudWatchQueryParameterCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope: any, templateSrv: TemplateSrv, uiSegmentSrv: any, datasourceSrv: DatasourceSrv, $q: IQService) { constructor($scope: any, templateSrv: TemplateSrv, uiSegmentSrv: any, datasourceSrv: DatasourceSrv) {
$scope.init = () => { $scope.init = () => {
const target = $scope.target; const target = $scope.target;
target.namespace = target.namespace || ''; target.namespace = target.namespace || '';
@@ -58,7 +58,7 @@ export class CloudWatchQueryParameterCtrl {
}; };
$scope.getStatSegments = () => { $scope.getStatSegments = () => {
return $q.when( return Promise.resolve(
_.flatten([ _.flatten([
angular.copy($scope.removeStatSegment), angular.copy($scope.removeStatSegment),
_.map($scope.datasource.standardStatistics, s => { _.map($scope.datasource.standardStatistics, s => {
@@ -102,11 +102,11 @@ export class CloudWatchQueryParameterCtrl {
$scope.getDimSegments = (segment: any, $index: number) => { $scope.getDimSegments = (segment: any, $index: number) => {
if (segment.type === 'operator') { if (segment.type === 'operator') {
return $q.when([]); return Promise.resolve([]);
} }
const target = $scope.target; const target = $scope.target;
let query = $q.when([]); let query = Promise.resolve([]);
if (segment.type === 'key' || segment.type === 'plus-button') { if (segment.type === 'key' || segment.type === 'plus-button') {
query = $scope.datasource.getDimensionKeys($scope.target.namespace, $scope.target.region); query = $scope.datasource.getDimensionKeys($scope.target.namespace, $scope.target.region);

View File

@@ -36,7 +36,7 @@ describe('CloudWatchDatasource', () => {
} as any; } as any;
beforeEach(() => { beforeEach(() => {
ctx.ds = new CloudWatchDatasource(instanceSettings, {} as any, backendSrv, templateSrv, timeSrv); ctx.ds = new CloudWatchDatasource(instanceSettings, backendSrv, templateSrv, timeSrv);
}); });
describe('When performing CloudWatch query', () => { describe('When performing CloudWatch query', () => {
@@ -313,7 +313,7 @@ describe('CloudWatchDatasource', () => {
ctx.backendSrv.datasourceRequest = jest.fn(() => { ctx.backendSrv.datasourceRequest = jest.fn(() => {
return Promise.resolve({}); return Promise.resolve({});
}); });
ctx.ds = new CloudWatchDatasource(instanceSettings, {} as any, backendSrv, templateSrv, timeSrv); ctx.ds = new CloudWatchDatasource(instanceSettings, backendSrv, templateSrv, timeSrv);
ctx.ds.doMetricQueryRequest = jest.fn(() => []); ctx.ds.doMetricQueryRequest = jest.fn(() => []);
}); });
describe('and region param is left out', () => { describe('and region param is left out', () => {

View File

@@ -1,13 +1,12 @@
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import _ from 'lodash'; import _ from 'lodash';
import * as queryDef from './query_def'; import * as queryDef from './query_def';
import { IQService } from 'angular';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl'; import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { CoreEvents } from 'app/types'; import { CoreEvents } from 'app/types';
export class ElasticBucketAggCtrl { export class ElasticBucketAggCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope: any, uiSegmentSrv: any, $q: IQService, $rootScope: GrafanaRootScope) { constructor($scope: any, uiSegmentSrv: any, $rootScope: GrafanaRootScope) {
const bucketAggs = $scope.target.bucketAggs; const bucketAggs = $scope.target.bucketAggs;
$scope.orderByOptions = []; $scope.orderByOptions = [];
@@ -182,7 +181,7 @@ export class ElasticBucketAggCtrl {
}; };
$scope.getIntervalOptions = () => { $scope.getIntervalOptions = () => {
return $q.when(uiSegmentSrv.transformToSegments(true, 'interval')(queryDef.intervalOptions)); return Promise.resolve(uiSegmentSrv.transformToSegments(true, 'interval')(queryDef.intervalOptions));
}; };
$scope.addBucketAgg = () => { $scope.addBucketAgg = () => {

View File

@@ -1,4 +1,4 @@
import angular, { IQService } from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import { DataSourceApi, DataSourceInstanceSettings, DataQueryRequest, DataQueryResponse } from '@grafana/data'; import { DataSourceApi, DataSourceInstanceSettings, DataQueryRequest, DataQueryResponse } from '@grafana/data';
import { ElasticResponse } from './elastic_response'; import { ElasticResponse } from './elastic_response';
@@ -29,7 +29,6 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
/** @ngInject */ /** @ngInject */
constructor( constructor(
instanceSettings: DataSourceInstanceSettings<ElasticsearchOptions>, instanceSettings: DataSourceInstanceSettings<ElasticsearchOptions>,
private $q: IQService,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
@@ -501,7 +500,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
metricFindQuery(query: any) { metricFindQuery(query: any) {
query = angular.fromJson(query); query = angular.fromJson(query);
if (!query) { if (!query) {
return this.$q.when([]); return Promise.resolve([]);
} }
if (query.find === 'fields') { if (query.find === 'fields') {

View File

@@ -2,13 +2,12 @@ import coreModule from 'app/core/core_module';
import _ from 'lodash'; import _ from 'lodash';
import * as queryDef from './query_def'; import * as queryDef from './query_def';
import { ElasticsearchAggregation } from './types'; import { ElasticsearchAggregation } from './types';
import { IQService } from 'angular';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl'; import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { CoreEvents } from 'app/types'; import { CoreEvents } from 'app/types';
export class ElasticMetricAggCtrl { export class ElasticMetricAggCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope: any, uiSegmentSrv: any, $q: IQService, $rootScope: GrafanaRootScope) { constructor($scope: any, uiSegmentSrv: any, $rootScope: GrafanaRootScope) {
const metricAggs: ElasticsearchAggregation[] = $scope.target.metrics; const metricAggs: ElasticsearchAggregation[] = $scope.target.metrics;
$scope.metricAggTypes = queryDef.getMetricAggTypes($scope.esVersion); $scope.metricAggTypes = queryDef.getMetricAggTypes($scope.esVersion);
$scope.extendedStats = queryDef.extendedStats; $scope.extendedStats = queryDef.extendedStats;

View File

@@ -1,4 +1,4 @@
import angular, { IQService } from 'angular'; import angular from 'angular';
import { dateMath } from '@grafana/data'; import { dateMath } from '@grafana/data';
import _ from 'lodash'; import _ from 'lodash';
import { ElasticDatasource } from '../datasource'; import { ElasticDatasource } from '../datasource';
@@ -52,7 +52,6 @@ describe('ElasticDatasource', function(this: any) {
instanceSettings.jsonData = instanceSettings.jsonData || ({} as ElasticsearchOptions); instanceSettings.jsonData = instanceSettings.jsonData || ({} as ElasticsearchOptions);
ctx.ds = new ElasticDatasource( ctx.ds = new ElasticDatasource(
instanceSettings, instanceSettings,
{} as IQService,
backendSrv as BackendSrv, backendSrv as BackendSrv,
templateSrv as TemplateSrv, templateSrv as TemplateSrv,
timeSrv as TimeSrv timeSrv as TimeSrv

View File

@@ -1,8 +1,6 @@
import Datasource from '../datasource'; import Datasource from '../datasource';
import { DataFrame, toUtc } from '@grafana/data'; import { DataFrame, toUtc } from '@grafana/data';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
// @ts-ignore
import Q from 'q';
describe('AppInsightsDatasource', () => { describe('AppInsightsDatasource', () => {
const ctx: any = { const ctx: any = {
@@ -11,13 +9,12 @@ describe('AppInsightsDatasource', () => {
}; };
beforeEach(() => { beforeEach(() => {
ctx.$q = Q;
ctx.instanceSettings = { ctx.instanceSettings = {
jsonData: { appInsightsAppId: '3ad4400f-ea7d-465d-a8fb-43fb20555d85' }, jsonData: { appInsightsAppId: '3ad4400f-ea7d-465d-a8fb-43fb20555d85' },
url: 'http://appinsightsapi', url: 'http://appinsightsapi',
}; };
ctx.ds = new Datasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv, ctx.$q); ctx.ds = new Datasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
}); });
describe('When performing testDatasource', () => { describe('When performing testDatasource', () => {
@@ -42,7 +39,7 @@ describe('AppInsightsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -67,7 +64,7 @@ describe('AppInsightsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.reject(error); return Promise.reject(error);
}; };
}); });
@@ -95,7 +92,7 @@ describe('AppInsightsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.reject(error); return Promise.reject(error);
}; };
}); });
@@ -162,7 +159,7 @@ describe('AppInsightsDatasource', () => {
expect(options.data.queries[0].appInsights.timeColumn).toEqual('timestamp'); expect(options.data.queries[0].appInsights.timeColumn).toEqual('timestamp');
expect(options.data.queries[0].appInsights.valueColumn).toEqual('max'); expect(options.data.queries[0].appInsights.valueColumn).toEqual('max');
expect(options.data.queries[0].appInsights.segmentColumn).toBeUndefined(); expect(options.data.queries[0].appInsights.segmentColumn).toBeUndefined();
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -205,7 +202,7 @@ describe('AppInsightsDatasource', () => {
expect(options.data.queries[0].appInsights.timeColumn).toEqual('timestamp'); expect(options.data.queries[0].appInsights.timeColumn).toEqual('timestamp');
expect(options.data.queries[0].appInsights.valueColumn).toEqual('max'); expect(options.data.queries[0].appInsights.valueColumn).toEqual('max');
expect(options.data.queries[0].appInsights.segmentColumn).toEqual('partition'); expect(options.data.queries[0].appInsights.segmentColumn).toEqual('partition');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -266,7 +263,7 @@ describe('AppInsightsDatasource', () => {
expect(options.data.queries[0].refId).toBe('A'); expect(options.data.queries[0].refId).toBe('A');
expect(options.data.queries[0].appInsights.rawQueryString).toBeUndefined(); expect(options.data.queries[0].appInsights.rawQueryString).toBeUndefined();
expect(options.data.queries[0].appInsights.metricName).toBe('exceptions/server'); expect(options.data.queries[0].appInsights.metricName).toBe('exceptions/server');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -309,7 +306,7 @@ describe('AppInsightsDatasource', () => {
expect(options.data.queries[0].appInsights.rawQueryString).toBeUndefined(); expect(options.data.queries[0].appInsights.rawQueryString).toBeUndefined();
expect(options.data.queries[0].appInsights.metricName).toBe('exceptions/server'); expect(options.data.queries[0].appInsights.metricName).toBe('exceptions/server');
expect(options.data.queries[0].appInsights.timeGrain).toBe('PT30M'); expect(options.data.queries[0].appInsights.timeGrain).toBe('PT30M');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -363,7 +360,7 @@ describe('AppInsightsDatasource', () => {
expect(options.data.queries[0].appInsights.rawQueryString).toBeUndefined(); expect(options.data.queries[0].appInsights.rawQueryString).toBeUndefined();
expect(options.data.queries[0].appInsights.metricName).toBe('exceptions/server'); expect(options.data.queries[0].appInsights.metricName).toBe('exceptions/server');
expect(options.data.queries[0].appInsights.dimension).toBe('client/city'); expect(options.data.queries[0].appInsights.dimension).toBe('client/city');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -402,7 +399,7 @@ describe('AppInsightsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('/metrics/metadata'); expect(options.url).toContain('/metrics/metadata');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -440,7 +437,7 @@ describe('AppInsightsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('/metrics/metadata'); expect(options.url).toContain('/metrics/metadata');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -468,7 +465,7 @@ describe('AppInsightsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('/metrics/metadata'); expect(options.url).toContain('/metrics/metadata');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -506,7 +503,7 @@ describe('AppInsightsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('/metrics/metadata'); expect(options.url).toContain('/metrics/metadata');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });

View File

@@ -1,7 +1,6 @@
import AzureMonitorDatasource from '../datasource'; import AzureMonitorDatasource from '../datasource';
import FakeSchemaData from './__mocks__/schema'; import FakeSchemaData from './__mocks__/schema';
// @ts-ignore
import Q from 'q';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { KustoSchema } from '../types'; import { KustoSchema } from '../types';
import { toUtc } from '@grafana/data'; import { toUtc } from '@grafana/data';
@@ -13,13 +12,12 @@ describe('AzureLogAnalyticsDatasource', () => {
}; };
beforeEach(() => { beforeEach(() => {
ctx.$q = Q;
ctx.instanceSettings = { ctx.instanceSettings = {
jsonData: { logAnalyticsSubscriptionId: 'xxx' }, jsonData: { logAnalyticsSubscriptionId: 'xxx' },
url: 'http://azureloganalyticsapi', url: 'http://azureloganalyticsapi',
}; };
ctx.ds = new AzureMonitorDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv, ctx.$q); ctx.ds = new AzureMonitorDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
}); });
describe('When the config option "Same as Azure Monitor" has been chosen', () => { describe('When the config option "Same as Azure Monitor" has been chosen', () => {
@@ -58,15 +56,15 @@ describe('AzureLogAnalyticsDatasource', () => {
ctx.instanceSettings.jsonData.tenantId = 'xxx'; ctx.instanceSettings.jsonData.tenantId = 'xxx';
ctx.instanceSettings.jsonData.clientId = 'xxx'; ctx.instanceSettings.jsonData.clientId = 'xxx';
ctx.instanceSettings.jsonData.azureLogAnalyticsSameAs = true; ctx.instanceSettings.jsonData.azureLogAnalyticsSameAs = true;
ctx.ds = new AzureMonitorDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv, ctx.$q); ctx.ds = new AzureMonitorDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
if (options.url.indexOf('Microsoft.OperationalInsights/workspaces') > -1) { if (options.url.indexOf('Microsoft.OperationalInsights/workspaces') > -1) {
workspacesUrl = options.url; workspacesUrl = options.url;
return ctx.$q.when({ data: workspaceResponse, status: 200 }); return Promise.resolve({ data: workspaceResponse, status: 200 });
} else { } else {
azureLogAnalyticsUrl = options.url; azureLogAnalyticsUrl = options.url;
return ctx.$q.when({ data: tableResponseWithOneColumn, status: 200 }); return Promise.resolve({ data: tableResponseWithOneColumn, status: 200 });
} }
}; };
@@ -97,7 +95,7 @@ describe('AzureLogAnalyticsDatasource', () => {
ctx.instanceSettings.jsonData.logAnalyticsTenantId = 'xxx'; ctx.instanceSettings.jsonData.logAnalyticsTenantId = 'xxx';
ctx.instanceSettings.jsonData.logAnalyticsClientId = 'xxx'; ctx.instanceSettings.jsonData.logAnalyticsClientId = 'xxx';
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.reject(error); return Promise.reject(error);
}; };
}); });
@@ -170,7 +168,7 @@ describe('AzureLogAnalyticsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('query=AzureActivity'); expect(options.url).toContain('query=AzureActivity');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -209,7 +207,7 @@ describe('AzureLogAnalyticsDatasource', () => {
}; };
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('query=AzureActivity'); expect(options.url).toContain('query=AzureActivity');
return ctx.$q.when({ data: invalidResponse, status: 200 }); return Promise.resolve({ data: invalidResponse, status: 200 });
}; };
}); });
@@ -226,7 +224,7 @@ describe('AzureLogAnalyticsDatasource', () => {
options.targets[0].azureLogAnalytics.resultFormat = 'table'; options.targets[0].azureLogAnalytics.resultFormat = 'table';
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('query=AzureActivity'); expect(options.url).toContain('query=AzureActivity');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -253,7 +251,7 @@ describe('AzureLogAnalyticsDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('metadata'); expect(options.url).toContain('metadata');
return ctx.$q.when({ data: FakeSchemaData.getlogAnalyticsFakeMetadata(), status: 200 }); return Promise.resolve({ data: FakeSchemaData.getlogAnalyticsFakeMetadata(), status: 200 });
}; };
}); });
@@ -306,9 +304,9 @@ describe('AzureLogAnalyticsDatasource', () => {
beforeEach(async () => { beforeEach(async () => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
if (options.url.indexOf('Microsoft.OperationalInsights/workspaces') > -1) { if (options.url.indexOf('Microsoft.OperationalInsights/workspaces') > -1) {
return ctx.$q.when({ data: workspaceResponse, status: 200 }); return Promise.resolve({ data: workspaceResponse, status: 200 });
} else { } else {
return ctx.$q.when({ data: tableResponseWithOneColumn, status: 200 }); return Promise.resolve({ data: tableResponseWithOneColumn, status: 200 });
} }
}; };
@@ -368,9 +366,9 @@ describe('AzureLogAnalyticsDatasource', () => {
beforeEach(async () => { beforeEach(async () => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
if (options.url.indexOf('Microsoft.OperationalInsights/workspaces') > -1) { if (options.url.indexOf('Microsoft.OperationalInsights/workspaces') > -1) {
return ctx.$q.when({ data: workspaceResponse, status: 200 }); return Promise.resolve({ data: workspaceResponse, status: 200 });
} else { } else {
return ctx.$q.when({ data: tableResponse, status: 200 }); return Promise.resolve({ data: tableResponse, status: 200 });
} }
}; };

View File

@@ -1,6 +1,5 @@
import AzureMonitorDatasource from '../datasource'; import AzureMonitorDatasource from '../datasource';
// @ts-ignore
import Q from 'q';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { toUtc, DataFrame } from '@grafana/data'; import { toUtc, DataFrame } from '@grafana/data';
@@ -11,14 +10,13 @@ describe('AzureMonitorDatasource', () => {
}; };
beforeEach(() => { beforeEach(() => {
ctx.$q = Q;
ctx.instanceSettings = { ctx.instanceSettings = {
url: 'http://azuremonitor.com', url: 'http://azuremonitor.com',
jsonData: { subscriptionId: '9935389e-9122-4ef9-95f9-1513dd24753f' }, jsonData: { subscriptionId: '9935389e-9122-4ef9-95f9-1513dd24753f' },
cloudName: 'azuremonitor', cloudName: 'azuremonitor',
}; };
ctx.ds = new AzureMonitorDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv, ctx.$q); ctx.ds = new AzureMonitorDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
}); });
describe('When performing testDatasource', () => { describe('When performing testDatasource', () => {
@@ -38,7 +36,7 @@ describe('AzureMonitorDatasource', () => {
ctx.instanceSettings.jsonData.tenantId = 'xxx'; ctx.instanceSettings.jsonData.tenantId = 'xxx';
ctx.instanceSettings.jsonData.clientId = 'xxx'; ctx.instanceSettings.jsonData.clientId = 'xxx';
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.reject(error); return Promise.reject(error);
}; };
}); });
@@ -65,7 +63,7 @@ describe('AzureMonitorDatasource', () => {
ctx.instanceSettings.jsonData.tenantId = 'xxx'; ctx.instanceSettings.jsonData.tenantId = 'xxx';
ctx.instanceSettings.jsonData.clientId = 'xxx'; ctx.instanceSettings.jsonData.clientId = 'xxx';
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -128,7 +126,7 @@ describe('AzureMonitorDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('/api/tsdb/query'); expect(options.url).toContain('/api/tsdb/query');
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
}); });
@@ -160,7 +158,7 @@ describe('AzureMonitorDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -186,7 +184,7 @@ describe('AzureMonitorDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -213,7 +211,7 @@ describe('AzureMonitorDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: { url: string }) => { ctx.backendSrv.datasourceRequest = (options: { url: string }) => {
expect(options.url).toContain('11112222-eeee-4949-9b2d-9106972f9123'); expect(options.url).toContain('11112222-eeee-4949-9b2d-9106972f9123');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -249,7 +247,7 @@ describe('AzureMonitorDatasource', () => {
const baseUrl = const baseUrl =
'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups'; 'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups';
expect(options.url).toBe(baseUrl + '/nodesapp/resources?api-version=2018-01-01'); expect(options.url).toBe(baseUrl + '/nodesapp/resources?api-version=2018-01-01');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -283,7 +281,7 @@ describe('AzureMonitorDatasource', () => {
const baseUrl = const baseUrl =
'http://azuremonitor.com/azuremonitor/subscriptions/11112222-eeee-4949-9b2d-9106972f9123/resourceGroups'; 'http://azuremonitor.com/azuremonitor/subscriptions/11112222-eeee-4949-9b2d-9106972f9123/resourceGroups';
expect(options.url).toBe(baseUrl + '/nodesapp/resources?api-version=2018-01-01'); expect(options.url).toBe(baseUrl + '/nodesapp/resources?api-version=2018-01-01');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -321,7 +319,7 @@ describe('AzureMonitorDatasource', () => {
const baseUrl = const baseUrl =
'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups'; 'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups';
expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01'); expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -359,7 +357,7 @@ describe('AzureMonitorDatasource', () => {
const baseUrl = const baseUrl =
'http://azuremonitor.com/azuremonitor/subscriptions/11112222-eeee-4949-9b2d-9106972f9123/resourceGroups'; 'http://azuremonitor.com/azuremonitor/subscriptions/11112222-eeee-4949-9b2d-9106972f9123/resourceGroups';
expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01'); expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -407,7 +405,7 @@ describe('AzureMonitorDatasource', () => {
'/nodeapp/providers/microsoft.insights/components/rn/providers/microsoft.insights/' + '/nodeapp/providers/microsoft.insights/components/rn/providers/microsoft.insights/' +
'metricdefinitions?api-version=2018-01-01&metricnamespace=default' 'metricdefinitions?api-version=2018-01-01&metricnamespace=default'
); );
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -456,7 +454,7 @@ describe('AzureMonitorDatasource', () => {
'/nodeapp/providers/microsoft.insights/components/rn/providers/microsoft.insights/' + '/nodeapp/providers/microsoft.insights/components/rn/providers/microsoft.insights/' +
'metricdefinitions?api-version=2018-01-01&metricnamespace=default' 'metricdefinitions?api-version=2018-01-01&metricnamespace=default'
); );
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -506,7 +504,7 @@ describe('AzureMonitorDatasource', () => {
baseUrl + baseUrl +
'/nodeapp/providers/Microsoft.Compute/virtualMachines/rn/providers/microsoft.insights/metricNamespaces?api-version=2017-12-01-preview' '/nodeapp/providers/Microsoft.Compute/virtualMachines/rn/providers/microsoft.insights/metricNamespaces?api-version=2017-12-01-preview'
); );
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -554,7 +552,7 @@ describe('AzureMonitorDatasource', () => {
baseUrl + baseUrl +
'/nodeapp/providers/Microsoft.Compute/virtualMachines/rn/providers/microsoft.insights/metricNamespaces?api-version=2017-12-01-preview' '/nodeapp/providers/Microsoft.Compute/virtualMachines/rn/providers/microsoft.insights/metricNamespaces?api-version=2017-12-01-preview'
); );
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -604,7 +602,7 @@ describe('AzureMonitorDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -628,7 +626,7 @@ describe('AzureMonitorDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = () => { ctx.backendSrv.datasourceRequest = () => {
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -680,7 +678,7 @@ describe('AzureMonitorDatasource', () => {
const baseUrl = const baseUrl =
'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups'; 'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups';
expect(options.url).toBe(baseUrl + '/nodesapp/resources?api-version=2018-01-01'); expect(options.url).toBe(baseUrl + '/nodesapp/resources?api-version=2018-01-01');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -731,7 +729,7 @@ describe('AzureMonitorDatasource', () => {
const baseUrl = const baseUrl =
'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups'; 'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups';
expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01'); expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -769,7 +767,7 @@ describe('AzureMonitorDatasource', () => {
const baseUrl = const baseUrl =
'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups'; 'http://azuremonitor.com/azuremonitor/subscriptions/9935389e-9122-4ef9-95f9-1513dd24753f/resourceGroups';
expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01'); expect(options.url).toBe(baseUrl + '/nodeapp/resources?api-version=2018-01-01');
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -838,7 +836,7 @@ describe('AzureMonitorDatasource', () => {
'/providers/microsoft.insights/components/resource1' + '/providers/microsoft.insights/components/resource1' +
'/providers/microsoft.insights/metricdefinitions?api-version=2018-01-01&metricnamespace=default'; '/providers/microsoft.insights/metricdefinitions?api-version=2018-01-01&metricnamespace=default';
expect(options.url).toBe(expected); expect(options.url).toBe(expected);
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -910,7 +908,7 @@ describe('AzureMonitorDatasource', () => {
'/providers/microsoft.insights/components/resource1' + '/providers/microsoft.insights/components/resource1' +
'/providers/microsoft.insights/metricdefinitions?api-version=2018-01-01&metricnamespace=default'; '/providers/microsoft.insights/metricdefinitions?api-version=2018-01-01&metricnamespace=default';
expect(options.url).toBe(expected); expect(options.url).toBe(expected);
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -984,7 +982,7 @@ describe('AzureMonitorDatasource', () => {
'/providers/microsoft.insights/components/resource1' + '/providers/microsoft.insights/components/resource1' +
'/providers/microsoft.insights/metricdefinitions?api-version=2018-01-01&metricnamespace=default'; '/providers/microsoft.insights/metricdefinitions?api-version=2018-01-01&metricnamespace=default';
expect(options.url).toBe(expected); expect(options.url).toBe(expected);
return ctx.$q.when(response); return Promise.resolve(response);
}; };
}); });

View File

@@ -6,7 +6,6 @@ import { AzureMonitorQuery, AzureDataSourceJsonData } from './types';
import { DataSourceApi, DataQueryRequest, DataSourceInstanceSettings } from '@grafana/data'; import { DataSourceApi, DataQueryRequest, DataSourceInstanceSettings } from '@grafana/data';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { IQService } from 'angular';
export default class Datasource extends DataSourceApi<AzureMonitorQuery, AzureDataSourceJsonData> { export default class Datasource extends DataSourceApi<AzureMonitorQuery, AzureDataSourceJsonData> {
azureMonitorDatasource: AzureMonitorDatasource; azureMonitorDatasource: AzureMonitorDatasource;
@@ -17,8 +16,7 @@ export default class Datasource extends DataSourceApi<AzureMonitorQuery, AzureDa
constructor( constructor(
instanceSettings: DataSourceInstanceSettings<AzureDataSourceJsonData>, instanceSettings: DataSourceInstanceSettings<AzureDataSourceJsonData>,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv
private $q: IQService
) { ) {
super(instanceSettings); super(instanceSettings);
this.azureMonitorDatasource = new AzureMonitorDatasource(instanceSettings, this.backendSrv, this.templateSrv); this.azureMonitorDatasource = new AzureMonitorDatasource(instanceSettings, this.backendSrv, this.templateSrv);
@@ -63,7 +61,7 @@ export default class Datasource extends DataSourceApi<AzureMonitorQuery, AzureDa
} }
if (promises.length === 0) { if (promises.length === 0) {
return this.$q.when({ data: [] }); return Promise.resolve({ data: [] });
} }
return Promise.all(promises).then(results => { return Promise.all(promises).then(results => {

View File

@@ -18,7 +18,6 @@ describe('AzureMonitorQueryCtrl', () => {
}; };
AzureMonitorQueryCtrl.prototype.target = {} as any; AzureMonitorQueryCtrl.prototype.target = {} as any;
AzureMonitorQueryCtrl.prototype.datasource = { AzureMonitorQueryCtrl.prototype.datasource = {
$q: Q,
appInsightsDatasource: { isConfigured: () => false }, appInsightsDatasource: { isConfigured: () => false },
azureMonitorDatasource: { isConfigured: () => false }, azureMonitorDatasource: { isConfigured: () => false },
}; };
@@ -54,7 +53,7 @@ describe('AzureMonitorQueryCtrl', () => {
beforeEach(() => { beforeEach(() => {
queryCtrl.datasource.getResourceGroups = () => { queryCtrl.datasource.getResourceGroups = () => {
return queryCtrl.datasource.$q.when(response); return Promise.resolve(response);
}; };
queryCtrl.datasource.azureMonitorDatasource = { queryCtrl.datasource.azureMonitorDatasource = {
isConfigured: () => { isConfigured: () => {
@@ -80,10 +79,10 @@ describe('AzureMonitorQueryCtrl', () => {
beforeEach(() => { beforeEach(() => {
queryCtrl.target.subscription = 'sub1'; queryCtrl.target.subscription = 'sub1';
queryCtrl.target.azureMonitor.resourceGroup = 'test'; queryCtrl.target.azureMonitor.resourceGroup = 'test';
queryCtrl.datasource.getMetricDefinitions = function(subscriptionId: any, query: any) { queryCtrl.datasource.getMetricDefinitions = (subscriptionId: any, query: any) => {
expect(subscriptionId).toBe('sub1'); expect(subscriptionId).toBe('sub1');
expect(query).toBe('test'); expect(query).toBe('test');
return this.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -117,15 +116,11 @@ describe('AzureMonitorQueryCtrl', () => {
queryCtrl.target.subscription = 'sub1'; queryCtrl.target.subscription = 'sub1';
queryCtrl.target.azureMonitor.resourceGroup = 'test'; queryCtrl.target.azureMonitor.resourceGroup = 'test';
queryCtrl.target.azureMonitor.metricDefinition = 'Microsoft.Compute/virtualMachines'; queryCtrl.target.azureMonitor.metricDefinition = 'Microsoft.Compute/virtualMachines';
queryCtrl.datasource.getResourceNames = function( queryCtrl.datasource.getResourceNames = (subscriptionId: any, resourceGroup: any, metricDefinition: any) => {
subscriptionId: any,
resourceGroup: any,
metricDefinition: any
) {
expect(subscriptionId).toBe('sub1'); expect(subscriptionId).toBe('sub1');
expect(resourceGroup).toBe('test'); expect(resourceGroup).toBe('test');
expect(metricDefinition).toBe('Microsoft.Compute/virtualMachines'); expect(metricDefinition).toBe('Microsoft.Compute/virtualMachines');
return this.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -162,19 +157,19 @@ describe('AzureMonitorQueryCtrl', () => {
queryCtrl.target.azureMonitor.metricDefinition = 'Microsoft.Compute/virtualMachines'; queryCtrl.target.azureMonitor.metricDefinition = 'Microsoft.Compute/virtualMachines';
queryCtrl.target.azureMonitor.resourceName = 'test'; queryCtrl.target.azureMonitor.resourceName = 'test';
queryCtrl.target.azureMonitor.metricNamespace = 'test'; queryCtrl.target.azureMonitor.metricNamespace = 'test';
queryCtrl.datasource.getMetricNames = function( queryCtrl.datasource.getMetricNames = (
subscriptionId: any, subscriptionId: any,
resourceGroup: any, resourceGroup: any,
metricDefinition: any, metricDefinition: any,
resourceName: any, resourceName: any,
metricNamespace: any metricNamespace: any
) { ) => {
expect(subscriptionId).toBe('sub1'); expect(subscriptionId).toBe('sub1');
expect(resourceGroup).toBe('test'); expect(resourceGroup).toBe('test');
expect(metricDefinition).toBe('Microsoft.Compute/virtualMachines'); expect(metricDefinition).toBe('Microsoft.Compute/virtualMachines');
expect(resourceName).toBe('test'); expect(resourceName).toBe('test');
expect(metricNamespace).toBe('test'); expect(metricNamespace).toBe('test');
return this.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -218,21 +213,21 @@ describe('AzureMonitorQueryCtrl', () => {
queryCtrl.target.azureMonitor.resourceName = 'test'; queryCtrl.target.azureMonitor.resourceName = 'test';
queryCtrl.target.azureMonitor.metricNamespace = 'test'; queryCtrl.target.azureMonitor.metricNamespace = 'test';
queryCtrl.target.azureMonitor.metricName = 'Percentage CPU'; queryCtrl.target.azureMonitor.metricName = 'Percentage CPU';
queryCtrl.datasource.getMetricMetadata = function( queryCtrl.datasource.getMetricMetadata = (
subscription: any, subscription: any,
resourceGroup: any, resourceGroup: any,
metricDefinition: any, metricDefinition: any,
resourceName: any, resourceName: any,
metricNamespace: any, metricNamespace: any,
metricName: any metricName: any
) { ) => {
expect(subscription).toBe('sub1'); expect(subscription).toBe('sub1');
expect(resourceGroup).toBe('test'); expect(resourceGroup).toBe('test');
expect(metricDefinition).toBe('Microsoft.Compute/virtualMachines'); expect(metricDefinition).toBe('Microsoft.Compute/virtualMachines');
expect(resourceName).toBe('test'); expect(resourceName).toBe('test');
expect(metricNamespace).toBe('test'); expect(metricNamespace).toBe('test');
expect(metricName).toBe('Percentage CPU'); expect(metricName).toBe('Percentage CPU');
return this.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -289,7 +284,7 @@ describe('AzureMonitorQueryCtrl', () => {
beforeEach(() => { beforeEach(() => {
queryCtrl.datasource.appInsightsDatasource.isConfigured = () => true; queryCtrl.datasource.appInsightsDatasource.isConfigured = () => true;
queryCtrl.datasource.getAppInsightsMetricNames = () => { queryCtrl.datasource.getAppInsightsMetricNames = () => {
return queryCtrl.datasource.$q.when(response); return Promise.resolve(response);
}; };
}); });
@@ -324,9 +319,9 @@ describe('AzureMonitorQueryCtrl', () => {
beforeEach(() => { beforeEach(() => {
queryCtrl.target.appInsights.metricName = 'requests/failed'; queryCtrl.target.appInsights.metricName = 'requests/failed';
queryCtrl.datasource.getAppInsightsMetricMetadata = function(metricName: string) { queryCtrl.datasource.getAppInsightsMetricMetadata = (metricName: string) => {
expect(metricName).toBe('requests/failed'); expect(metricName).toBe('requests/failed');
return this.$q.when(response); return Promise.resolve(response);
}; };
}); });

View File

@@ -1,11 +1,10 @@
import _ from 'lodash'; import _ from 'lodash';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { IQService } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
class GrafanaDatasource { class GrafanaDatasource {
/** @ngInject */ /** @ngInject */
constructor(private backendSrv: BackendSrv, private $q: IQService, private templateSrv: TemplateSrv) {} constructor(private backendSrv: BackendSrv, private templateSrv: TemplateSrv) {}
query(options: any) { query(options: any) {
return this.backendSrv return this.backendSrv
@@ -34,7 +33,7 @@ class GrafanaDatasource {
} }
metricFindQuery(options: any) { metricFindQuery(options: any) {
return this.$q.when({ data: [] }); return Promise.resolve({ data: [] });
} }
annotationQuery(options: any) { annotationQuery(options: any) {
@@ -49,7 +48,7 @@ class GrafanaDatasource {
if (options.annotation.type === 'dashboard') { if (options.annotation.type === 'dashboard') {
// if no dashboard id yet return // if no dashboard id yet return
if (!options.dashboard.id) { if (!options.dashboard.id) {
return this.$q.when([]); return Promise.resolve([]);
} }
// filter by dashboard id // filter by dashboard id
params.dashboardId = options.dashboard.id; params.dashboardId = options.dashboard.id;
@@ -58,7 +57,7 @@ class GrafanaDatasource {
} else { } else {
// require at least one tag // require at least one tag
if (!_.isArray(options.annotation.tags) || options.annotation.tags.length === 0) { if (!_.isArray(options.annotation.tags) || options.annotation.tags.length === 0) {
return this.$q.when([]); return Promise.resolve([]);
} }
const delimiter = '__delimiter__'; const delimiter = '__delimiter__';
const tags = []; const tags = [];

View File

@@ -19,7 +19,7 @@ describe('grafana data source', () => {
}, },
}; };
const ds = new GrafanaDatasource(backendSrvStub as any, q, templateSrvStub as any); const ds = new GrafanaDatasource(backendSrvStub as any, templateSrvStub as any);
describe('with tags that have template variables', () => { describe('with tags that have template variables', () => {
const options = setupAnnotationQueryOptions({ tags: ['tag1:$var'] }); const options = setupAnnotationQueryOptions({ tags: ['tag1:$var'] });

View File

@@ -10,7 +10,6 @@ import {
} from '@grafana/data'; } from '@grafana/data';
import { isVersionGtOrEq, SemVersion } from 'app/core/utils/version'; import { isVersionGtOrEq, SemVersion } from 'app/core/utils/version';
import gfunc from './gfunc'; import gfunc from './gfunc';
import { IQService } from 'angular';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
//Types //Types
@@ -31,12 +30,7 @@ export class GraphiteDatasource extends DataSourceApi<GraphiteQuery, GraphiteOpt
_seriesRefLetters: string; _seriesRefLetters: string;
/** @ngInject */ /** @ngInject */
constructor( constructor(instanceSettings: any, private backendSrv: BackendSrv, private templateSrv: TemplateSrv) {
instanceSettings: any,
private $q: IQService,
private backendSrv: BackendSrv,
private templateSrv: TemplateSrv
) {
super(instanceSettings); super(instanceSettings);
this.basicAuth = instanceSettings.basicAuth; this.basicAuth = instanceSettings.basicAuth;
this.url = instanceSettings.url; this.url = instanceSettings.url;
@@ -76,7 +70,7 @@ export class GraphiteDatasource extends DataSourceApi<GraphiteQuery, GraphiteOpt
const params = this.buildGraphiteParams(graphOptions, options.scopedVars); const params = this.buildGraphiteParams(graphOptions, options.scopedVars);
if (params.length === 0) { if (params.length === 0) {
return this.$q.when({ data: [] }); return Promise.resolve({ data: [] });
} }
if (this.isMetricTank) { if (this.isMetricTank) {
@@ -244,7 +238,7 @@ export class GraphiteDatasource extends DataSourceApi<GraphiteQuery, GraphiteOpt
tags, tags,
}); });
} catch (err) { } catch (err) {
return this.$q.reject(err); return Promise.reject(err);
} }
} }

View File

@@ -1,14 +1,12 @@
import { GraphiteDatasource } from '../datasource'; import { GraphiteDatasource } from '../datasource';
import _ from 'lodash'; import _ from 'lodash';
// @ts-ignore
import $q from 'q';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { dateTime } from '@grafana/data'; import { dateTime } from '@grafana/data';
describe('graphiteDatasource', () => { describe('graphiteDatasource', () => {
const ctx: any = { const ctx: any = {
backendSrv: {}, backendSrv: {},
$q,
// @ts-ignore // @ts-ignore
templateSrv: new TemplateSrv(), templateSrv: new TemplateSrv(),
instanceSettings: { url: 'url', name: 'graphiteProd', jsonData: {} }, instanceSettings: { url: 'url', name: 'graphiteProd', jsonData: {} },
@@ -17,7 +15,7 @@ describe('graphiteDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.instanceSettings.url = '/api/datasources/proxy/1'; ctx.instanceSettings.url = '/api/datasources/proxy/1';
// @ts-ignore // @ts-ignore
ctx.ds = new GraphiteDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); ctx.ds = new GraphiteDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
}); });
describe('When querying graphite with one target using query editor target spec', () => { describe('When querying graphite with one target using query editor target spec', () => {
@@ -35,7 +33,7 @@ describe('graphiteDatasource', () => {
beforeEach(async () => { beforeEach(async () => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
requestOptions = options; requestOptions = options;
return ctx.$q.when({ return Promise.resolve({
data: [ data: [
{ {
target: 'prod1.count', target: 'prod1.count',
@@ -118,7 +116,7 @@ describe('graphiteDatasource', () => {
beforeEach(async () => { beforeEach(async () => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
return ctx.$q.when(response); return Promise.resolve(response);
}; };
await ctx.ds.annotationQuery(options).then((data: any) => { await ctx.ds.annotationQuery(options).then((data: any) => {
@@ -148,7 +146,7 @@ describe('graphiteDatasource', () => {
}; };
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
return ctx.$q.when(response); return Promise.resolve(response);
}; };
ctx.ds.annotationQuery(options).then((data: any) => { ctx.ds.annotationQuery(options).then((data: any) => {
@@ -267,7 +265,7 @@ describe('graphiteDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
requestOptions = options; requestOptions = options;
return ctx.$q.when({ return Promise.resolve({
data: ['backend_01', 'backend_02'], data: ['backend_01', 'backend_02'],
}); });
}; };
@@ -393,7 +391,6 @@ function accessScenario(name: string, url: string, fn: any) {
describe('access scenario ' + name, () => { describe('access scenario ' + name, () => {
const ctx: any = { const ctx: any = {
backendSrv: {}, backendSrv: {},
$q,
// @ts-ignore // @ts-ignore
templateSrv: new TemplateSrv(), templateSrv: new TemplateSrv(),
instanceSettings: { url: 'url', name: 'graphiteProd', jsonData: {} }, instanceSettings: { url: 'url', name: 'graphiteProd', jsonData: {} },
@@ -409,7 +406,7 @@ function accessScenario(name: string, url: string, fn: any) {
it('tracing headers should be added', () => { it('tracing headers should be added', () => {
ctx.instanceSettings.url = url; ctx.instanceSettings.url = url;
// @ts-ignore // @ts-ignore
const ds = new GraphiteDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); const ds = new GraphiteDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
ds.addTracingHeaders(httpOptions, options); ds.addTracingHeaders(httpOptions, options);
fn(httpOptions); fn(httpOptions);
}); });

View File

@@ -8,7 +8,6 @@ import { InfluxQueryBuilder } from './query_builder';
import { InfluxQuery, InfluxOptions } from './types'; import { InfluxQuery, InfluxOptions } from './types';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { IQService } from 'angular';
export default class InfluxDatasource extends DataSourceApi<InfluxQuery, InfluxOptions> { export default class InfluxDatasource extends DataSourceApi<InfluxQuery, InfluxOptions> {
type: string; type: string;
@@ -26,7 +25,6 @@ export default class InfluxDatasource extends DataSourceApi<InfluxQuery, InfluxO
/** @ngInject */ /** @ngInject */
constructor( constructor(
instanceSettings: DataSourceInstanceSettings<InfluxOptions>, instanceSettings: DataSourceInstanceSettings<InfluxOptions>,
private $q: IQService,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private templateSrv: TemplateSrv private templateSrv: TemplateSrv
) { ) {
@@ -76,7 +74,7 @@ export default class InfluxDatasource extends DataSourceApi<InfluxQuery, InfluxO
}); });
if (allQueries === '') { if (allQueries === '') {
return this.$q.when({ data: [] }); return Promise.resolve({ data: [] });
} }
// add global adhoc filters to timeFilter // add global adhoc filters to timeFilter
@@ -135,7 +133,7 @@ export default class InfluxDatasource extends DataSourceApi<InfluxQuery, InfluxO
annotationQuery(options: any) { annotationQuery(options: any) {
if (!options.annotation.query) { if (!options.annotation.query) {
return this.$q.reject({ return Promise.reject({
message: 'Query missing in annotation definition', message: 'Query missing in annotation definition',
}); });
} }
@@ -227,7 +225,7 @@ export default class InfluxDatasource extends DataSourceApi<InfluxQuery, InfluxO
_seriesQuery(query: string, options?: any) { _seriesQuery(query: string, options?: any) {
if (!query) { if (!query) {
return this.$q.when({ results: [] }); return Promise.resolve({ results: [] });
} }
if (options && options.range) { if (options && options.range) {

View File

@@ -1,4 +1,4 @@
import angular, { auto, IQService } from 'angular'; import angular, { auto } from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import { InfluxQueryBuilder } from './query_builder'; import { InfluxQueryBuilder } from './query_builder';
import InfluxQueryModel from './influx_query_model'; import InfluxQueryModel from './influx_query_model';
@@ -25,7 +25,6 @@ export class InfluxQueryCtrl extends QueryCtrl {
$scope: any, $scope: any,
$injector: auto.IInjectorService, $injector: auto.IInjectorService,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private $q: IQService,
private uiSegmentSrv: any private uiSegmentSrv: any
) { ) {
super($scope, $injector); super($scope, $injector);
@@ -180,7 +179,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -204,7 +203,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -285,14 +284,14 @@ export class InfluxQueryCtrl extends QueryCtrl {
getTagsOrValues(segment: { type: string }, index: number) { getTagsOrValues(segment: { type: string }, index: number) {
if (segment.type === 'condition') { if (segment.type === 'condition') {
return this.$q.when([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]); return Promise.resolve([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]);
} }
if (segment.type === 'operator') { if (segment.type === 'operator') {
const nextValue = this.tagSegments[index + 1].value; const nextValue = this.tagSegments[index + 1].value;
if (/^\/.*\/$/.test(nextValue)) { if (/^\/.*\/$/.test(nextValue)) {
return this.$q.when(this.uiSegmentSrv.newOperators(['=~', '!~'])); return Promise.resolve(this.uiSegmentSrv.newOperators(['=~', '!~']));
} else { } else {
return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<>', '<', '>'])); return Promise.resolve(this.uiSegmentSrv.newOperators(['=', '!=', '<>', '<', '>']));
} }
} }

View File

@@ -1,12 +1,10 @@
import InfluxDatasource from '../datasource'; import InfluxDatasource from '../datasource';
//@ts-ignore
import $q from 'q';
import { TemplateSrvStub } from 'test/specs/helpers'; import { TemplateSrvStub } from 'test/specs/helpers';
describe('InfluxDataSource', () => { describe('InfluxDataSource', () => {
const ctx: any = { const ctx: any = {
backendSrv: {}, backendSrv: {},
$q: $q,
//@ts-ignore //@ts-ignore
templateSrv: new TemplateSrvStub(), templateSrv: new TemplateSrvStub(),
instanceSettings: { url: 'url', name: 'influxDb', jsonData: { httpMode: 'GET' } }, instanceSettings: { url: 'url', name: 'influxDb', jsonData: { httpMode: 'GET' } },
@@ -14,7 +12,7 @@ describe('InfluxDataSource', () => {
beforeEach(() => { beforeEach(() => {
ctx.instanceSettings.url = '/api/datasources/proxy/1'; ctx.instanceSettings.url = '/api/datasources/proxy/1';
ctx.ds = new InfluxDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); ctx.ds = new InfluxDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
}); });
describe('When issuing metricFindQuery', () => { describe('When issuing metricFindQuery', () => {
@@ -32,7 +30,7 @@ describe('InfluxDataSource', () => {
requestMethod = req.method; requestMethod = req.method;
requestQuery = req.params.q; requestQuery = req.params.q;
requestData = req.data; requestData = req.data;
return ctx.$q.when({ return Promise.resolve({
results: [ results: [
{ {
series: [ series: [
@@ -67,7 +65,6 @@ describe('InfluxDataSource', () => {
describe('InfluxDataSource in POST query mode', () => { describe('InfluxDataSource in POST query mode', () => {
const ctx: any = { const ctx: any = {
backendSrv: {}, backendSrv: {},
$q,
//@ts-ignore //@ts-ignore
templateSrv: new TemplateSrvStub(), templateSrv: new TemplateSrvStub(),
instanceSettings: { url: 'url', name: 'influxDb', jsonData: { httpMode: 'POST' } }, instanceSettings: { url: 'url', name: 'influxDb', jsonData: { httpMode: 'POST' } },
@@ -75,7 +72,7 @@ describe('InfluxDataSource in POST query mode', () => {
beforeEach(() => { beforeEach(() => {
ctx.instanceSettings.url = '/api/datasources/proxy/1'; ctx.instanceSettings.url = '/api/datasources/proxy/1';
ctx.ds = new InfluxDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); ctx.ds = new InfluxDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.templateSrv);
}); });
describe('When issuing metricFindQuery', () => { describe('When issuing metricFindQuery', () => {
@@ -88,7 +85,7 @@ describe('InfluxDataSource in POST query mode', () => {
requestMethod = req.method; requestMethod = req.method;
requestQueryParameter = req.params; requestQueryParameter = req.params;
requestQuery = req.data; requestQuery = req.data;
return ctx.$q.when({ return Promise.resolve({
results: [ results: [
{ {
series: [ series: [

View File

@@ -21,7 +21,6 @@ describe('InfluxDBQueryCtrl', () => {
{}, {},
{} as any, {} as any,
{} as any, {} as any,
{} as any,
//@ts-ignore //@ts-ignore
new uiSegmentSrv({ trustAsHtml: (html: any) => html }, { highlightVariablesAsHtml: () => {} }) new uiSegmentSrv({ trustAsHtml: (html: any) => html }, { highlightVariablesAsHtml: () => {} })
); );

View File

@@ -1,7 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import ResponseParser from './response_parser'; import ResponseParser from './response_parser';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { IQService } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
//Types //Types
@@ -17,13 +16,12 @@ export class MssqlDatasource {
constructor( constructor(
instanceSettings: any, instanceSettings: any,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private $q: IQService,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
) { ) {
this.name = instanceSettings.name; this.name = instanceSettings.name;
this.id = instanceSettings.id; this.id = instanceSettings.id;
this.responseParser = new ResponseParser(this.$q); this.responseParser = new ResponseParser();
this.interval = (instanceSettings.jsonData || {}).timeInterval || '1m'; this.interval = (instanceSettings.jsonData || {}).timeInterval || '1m';
} }
@@ -80,7 +78,7 @@ export class MssqlDatasource {
}); });
if (queries.length === 0) { if (queries.length === 0) {
return this.$q.when({ data: [] }); return Promise.resolve({ data: [] });
} }
return this.backendSrv return this.backendSrv
@@ -98,7 +96,7 @@ export class MssqlDatasource {
annotationQuery(options: any) { annotationQuery(options: any) {
if (!options.annotation.rawQuery) { if (!options.annotation.rawQuery) {
return this.$q.reject({ message: 'Query missing in annotation definition' }); return Promise.reject({ message: 'Query missing in annotation definition' });
} }
const query = { const query = {

View File

@@ -1,9 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import { IQService } from 'angular';
export default class ResponseParser { export default class ResponseParser {
constructor(private $q: IQService) {}
processQueryResult(res: any) { processQueryResult(res: any) {
const data: any[] = []; const data: any[] = [];
@@ -121,7 +118,7 @@ export default class ResponseParser {
} }
if (timeColumnIndex === -1) { if (timeColumnIndex === -1) {
return this.$q.reject({ message: 'Missing mandatory time column (with time column alias) in annotation query.' }); return Promise.reject({ message: 'Missing mandatory time column (with time column alias) in annotation query.' });
} }
const list = []; const list = [];

View File

@@ -1,8 +1,7 @@
import { MssqlDatasource } from '../datasource'; import { MssqlDatasource } from '../datasource';
import { TimeSrvStub } from 'test/specs/helpers'; import { TimeSrvStub } from 'test/specs/helpers';
import { CustomVariable } from 'app/features/templating/custom_variable'; import { CustomVariable } from 'app/features/templating/custom_variable';
// @ts-ignore
import q from 'q';
import { dateTime } from '@grafana/data'; import { dateTime } from '@grafana/data';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
@@ -15,10 +14,9 @@ describe('MSSQLDatasource', () => {
}; };
beforeEach(() => { beforeEach(() => {
ctx.$q = q;
ctx.instanceSettings = { name: 'mssql' }; ctx.instanceSettings = { name: 'mssql' };
ctx.ds = new MssqlDatasource(ctx.instanceSettings, ctx.backendSrv, ctx.$q, templateSrv, ctx.timeSrv); ctx.ds = new MssqlDatasource(ctx.instanceSettings, ctx.backendSrv, templateSrv, ctx.timeSrv);
}); });
describe('When performing annotationQuery', () => { describe('When performing annotationQuery', () => {
@@ -57,7 +55,7 @@ describe('MSSQLDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
return ctx.ds.annotationQuery(options).then((data: any) => { return ctx.ds.annotationQuery(options).then((data: any) => {
@@ -105,7 +103,7 @@ describe('MSSQLDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
return ctx.ds.metricFindQuery(query).then((data: any) => { return ctx.ds.metricFindQuery(query).then((data: any) => {
@@ -146,7 +144,7 @@ describe('MSSQLDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
return ctx.ds.metricFindQuery(query).then((data: any) => { return ctx.ds.metricFindQuery(query).then((data: any) => {
@@ -189,7 +187,7 @@ describe('MSSQLDatasource', () => {
beforeEach(() => { beforeEach(() => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
return ctx.ds.metricFindQuery(query).then((data: any) => { return ctx.ds.metricFindQuery(query).then((data: any) => {
@@ -233,7 +231,7 @@ describe('MSSQLDatasource', () => {
ctx.backendSrv.datasourceRequest = (options: any) => { ctx.backendSrv.datasourceRequest = (options: any) => {
results = options.data; results = options.data;
return ctx.$q.when({ data: response, status: 200 }); return Promise.resolve({ data: response, status: 200 });
}; };
return ctx.ds.metricFindQuery(query); return ctx.ds.metricFindQuery(query);

View File

@@ -2,7 +2,6 @@ import _ from 'lodash';
import ResponseParser from './response_parser'; import ResponseParser from './response_parser';
import MysqlQuery from 'app/plugins/datasource/mysql/mysql_query'; import MysqlQuery from 'app/plugins/datasource/mysql/mysql_query';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { IQService } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
//Types //Types
@@ -20,13 +19,12 @@ export class MysqlDatasource {
constructor( constructor(
instanceSettings: any, instanceSettings: any,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private $q: IQService,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
) { ) {
this.name = instanceSettings.name; this.name = instanceSettings.name;
this.id = instanceSettings.id; this.id = instanceSettings.id;
this.responseParser = new ResponseParser(this.$q); this.responseParser = new ResponseParser();
this.queryModel = new MysqlQuery({}); this.queryModel = new MysqlQuery({});
this.interval = (instanceSettings.jsonData || {}).timeInterval || '1m'; this.interval = (instanceSettings.jsonData || {}).timeInterval || '1m';
} }
@@ -82,7 +80,7 @@ export class MysqlDatasource {
}); });
if (queries.length === 0) { if (queries.length === 0) {
return this.$q.when({ data: [] }); return Promise.resolve({ data: [] });
} }
return this.backendSrv return this.backendSrv
@@ -100,7 +98,7 @@ export class MysqlDatasource {
annotationQuery(options: any) { annotationQuery(options: any) {
if (!options.annotation.rawQuery) { if (!options.annotation.rawQuery) {
return this.$q.reject({ return Promise.reject({
message: 'Query missing in annotation definition', message: 'Query missing in annotation definition',
}); });
} }

View File

@@ -5,7 +5,7 @@ import { QueryCtrl } from 'app/plugins/sdk';
import { SqlPart } from 'app/core/components/sql_part/sql_part'; import { SqlPart } from 'app/core/components/sql_part/sql_part';
import MysqlQuery from './mysql_query'; import MysqlQuery from './mysql_query';
import sqlPart from './sql_part'; import sqlPart from './sql_part';
import { auto, IQService } from 'angular'; import { auto } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { CoreEvents } from 'app/types'; import { CoreEvents } from 'app/types';
import { PanelEvents } from '@grafana/data'; import { PanelEvents } from '@grafana/data';
@@ -49,7 +49,6 @@ export class MysqlQueryCtrl extends QueryCtrl {
$scope: any, $scope: any,
$injector: auto.IInjectorService, $injector: auto.IInjectorService,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private $q: IQService,
private uiSegmentSrv: any private uiSegmentSrv: any
) { ) {
super($scope, $injector); super($scope, $injector);
@@ -217,7 +216,7 @@ export class MysqlQueryCtrl extends QueryCtrl {
} }
}); });
this.$q.all([task1, task2]).then(() => { Promise.all([task1, task2]).then(() => {
this.updateRawSqlAndRefresh(); this.updateRawSqlAndRefresh();
}); });
} }
@@ -449,7 +448,7 @@ export class MysqlQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -473,7 +472,7 @@ export class MysqlQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -536,7 +535,7 @@ export class MysqlQueryCtrl extends QueryCtrl {
case 'right': case 'right':
if (['int', 'bigint', 'double', 'datetime'].indexOf(part.datatype) > -1) { if (['int', 'bigint', 'double', 'datetime'].indexOf(part.datatype) > -1) {
// don't do value lookups for numerical fields // don't do value lookups for numerical fields
return this.$q.when([]); return Promise.resolve([]);
} else { } else {
return this.datasource return this.datasource
.metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0])) .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
@@ -551,9 +550,9 @@ export class MysqlQueryCtrl extends QueryCtrl {
.catch(this.handleQueryError.bind(this)); .catch(this.handleQueryError.bind(this));
} }
case 'op': case 'op':
return this.$q.when(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype))); return Promise.resolve(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype)));
default: default:
return this.$q.when([]); return Promise.resolve([]);
} }
} }
case 'part-param-changed': { case 'part-param-changed': {
@@ -574,7 +573,7 @@ export class MysqlQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -587,7 +586,7 @@ export class MysqlQueryCtrl extends QueryCtrl {
options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' })); options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
} }
options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' })); options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
return this.$q.when(options); return Promise.resolve(options);
} }
addWhereAction(part: any, index: number) { addWhereAction(part: any, index: number) {

View File

@@ -1,9 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import { IQService } from 'angular';
export default class ResponseParser { export default class ResponseParser {
constructor(private $q: IQService) {}
processQueryResult(res: any) { processQueryResult(res: any) {
const data: any[] = []; const data: any[] = [];
@@ -117,7 +114,7 @@ export default class ResponseParser {
if (table.columns[i].text === 'time_sec' || table.columns[i].text === 'time') { if (table.columns[i].text === 'time_sec' || table.columns[i].text === 'time') {
timeColumnIndex = i; timeColumnIndex = i;
} else if (table.columns[i].text === 'title') { } else if (table.columns[i].text === 'title') {
return this.$q.reject({ return Promise.reject({
message: 'The title column for annotations is deprecated, now only a column named text is returned', message: 'The title column for annotations is deprecated, now only a column named text is returned',
}); });
} else if (table.columns[i].text === 'text') { } else if (table.columns[i].text === 'text') {
@@ -128,7 +125,7 @@ export default class ResponseParser {
} }
if (timeColumnIndex === -1) { if (timeColumnIndex === -1) {
return this.$q.reject({ return Promise.reject({
message: 'Missing mandatory time column (with time_sec column alias) in annotation query.', message: 'Missing mandatory time column (with time_sec column alias) in annotation query.',
}); });
} }

View File

@@ -25,7 +25,7 @@ describe('MySQLDatasource', () => {
} as any; } as any;
beforeEach(() => { beforeEach(() => {
ctx.ds = new MysqlDatasource(instanceSettings, backendSrv as BackendSrv, {} as any, templateSrv, ctx.timeSrvMock); ctx.ds = new MysqlDatasource(instanceSettings, backendSrv as BackendSrv, templateSrv, ctx.timeSrvMock);
}); });
describe('When performing annotationQuery', () => { describe('When performing annotationQuery', () => {

View File

@@ -1,4 +1,4 @@
import angular, { IQService } from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import { dateMath, DataQueryRequest, DataSourceApi } from '@grafana/data'; import { dateMath, DataQueryRequest, DataSourceApi } from '@grafana/data';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
@@ -18,14 +18,9 @@ export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenT
aggregatorsPromise: any; aggregatorsPromise: any;
filterTypesPromise: any; filterTypesPromise: any;
/** @ngInject */ constructor(instanceSettings: any, private backendSrv: BackendSrv, private templateSrv: TemplateSrv) {
constructor(
instanceSettings: any,
private $q: IQService,
private backendSrv: BackendSrv,
private templateSrv: TemplateSrv
) {
super(instanceSettings); super(instanceSettings);
this.type = 'opentsdb'; this.type = 'opentsdb';
this.url = instanceSettings.url; this.url = instanceSettings.url;
this.name = instanceSettings.name; this.name = instanceSettings.name;
@@ -57,9 +52,7 @@ export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenT
// No valid targets, return the empty result to save a round trip. // No valid targets, return the empty result to save a round trip.
if (_.isEmpty(queries)) { if (_.isEmpty(queries)) {
const d = this.$q.defer(); return Promise.resolve({ data: [] });
d.resolve({ data: [] });
return d.promise;
} }
const groupByTags: any = {}; const groupByTags: any = {};
@@ -177,7 +170,7 @@ export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenT
} }
suggestTagKeys(metric: string | number) { suggestTagKeys(metric: string | number) {
return this.$q.when(this.tagKeys[metric] || []); return Promise.resolve(this.tagKeys[metric] || []);
} }
_saveTagKeys(metricData: { tags: {}; aggregateTags: any; metric: string | number }) { _saveTagKeys(metricData: { tags: {}; aggregateTags: any; metric: string | number }) {
@@ -197,7 +190,7 @@ export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenT
_performMetricKeyValueLookup(metric: string, keys: any) { _performMetricKeyValueLookup(metric: string, keys: any) {
if (!metric || !keys) { if (!metric || !keys) {
return this.$q.when([]); return Promise.resolve([]);
} }
const keysArray = keys.split(',').map((key: any) => { const keysArray = keys.split(',').map((key: any) => {
@@ -226,7 +219,7 @@ export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenT
_performMetricKeyLookup(metric: any) { _performMetricKeyLookup(metric: any) {
if (!metric) { if (!metric) {
return this.$q.when([]); return Promise.resolve([]);
} }
return this._get('/api/search/lookup', { m: metric, limit: 1000 }).then((result: any) => { return this._get('/api/search/lookup', { m: metric, limit: 1000 }).then((result: any) => {
@@ -266,14 +259,14 @@ export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenT
metricFindQuery(query: string) { metricFindQuery(query: string) {
if (!query) { if (!query) {
return this.$q.when([]); return Promise.resolve([]);
} }
let interpolated; let interpolated;
try { try {
interpolated = this.templateSrv.replace(query, {}, 'distributed'); interpolated = this.templateSrv.replace(query, {}, 'distributed');
} catch (err) { } catch (err) {
return this.$q.reject(err); return Promise.reject(err);
} }
const responseTransform = (result: any) => { const responseTransform = (result: any) => {
@@ -313,7 +306,7 @@ export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenT
return this._performSuggestQuery(tagValuesSuggestQuery[1], 'tagv').then(responseTransform); return this._performSuggestQuery(tagValuesSuggestQuery[1], 'tagv').then(responseTransform);
} }
return this.$q.when([]); return Promise.resolve([]);
} }
testDatasource() { testDatasource() {

View File

@@ -1,6 +1,4 @@
import OpenTsDatasource from '../datasource'; import OpenTsDatasource from '../datasource';
// @ts-ignore
import $q from 'q';
describe('opentsdb', () => { describe('opentsdb', () => {
const ctx = { const ctx = {
@@ -13,7 +11,7 @@ describe('opentsdb', () => {
const instanceSettings = { url: '', jsonData: { tsdbVersion: 1 } }; const instanceSettings = { url: '', jsonData: { tsdbVersion: 1 } };
beforeEach(() => { beforeEach(() => {
ctx.ctrl = new OpenTsDatasource(instanceSettings, $q, ctx.backendSrv, ctx.templateSrv); ctx.ctrl = new OpenTsDatasource(instanceSettings, ctx.backendSrv, ctx.templateSrv);
}); });
describe('When performing metricFindQuery', () => { describe('When performing metricFindQuery', () => {

View File

@@ -1,7 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import ResponseParser from './response_parser'; import ResponseParser from './response_parser';
import PostgresQuery from 'app/plugins/datasource/postgres/postgres_query'; import PostgresQuery from 'app/plugins/datasource/postgres/postgres_query';
import { IQService } from 'angular';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
@@ -21,14 +20,13 @@ export class PostgresDatasource {
constructor( constructor(
instanceSettings: { name: any; id?: any; jsonData?: any }, instanceSettings: { name: any; id?: any; jsonData?: any },
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private $q: IQService,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
) { ) {
this.name = instanceSettings.name; this.name = instanceSettings.name;
this.id = instanceSettings.id; this.id = instanceSettings.id;
this.jsonData = instanceSettings.jsonData; this.jsonData = instanceSettings.jsonData;
this.responseParser = new ResponseParser(this.$q); this.responseParser = new ResponseParser();
this.queryModel = new PostgresQuery({}); this.queryModel = new PostgresQuery({});
this.interval = (instanceSettings.jsonData || {}).timeInterval || '1m'; this.interval = (instanceSettings.jsonData || {}).timeInterval || '1m';
} }
@@ -84,7 +82,7 @@ export class PostgresDatasource {
}); });
if (queries.length === 0) { if (queries.length === 0) {
return this.$q.when({ data: [] }); return Promise.resolve({ data: [] });
} }
return this.backendSrv return this.backendSrv
@@ -102,7 +100,7 @@ export class PostgresDatasource {
annotationQuery(options: any) { annotationQuery(options: any) {
if (!options.annotation.rawQuery) { if (!options.annotation.rawQuery) {
return this.$q.reject({ return Promise.reject({
message: 'Query missing in annotation definition', message: 'Query missing in annotation definition',
}); });
} }

View File

@@ -5,7 +5,7 @@ import { QueryCtrl } from 'app/plugins/sdk';
import { SqlPart } from 'app/core/components/sql_part/sql_part'; import { SqlPart } from 'app/core/components/sql_part/sql_part';
import PostgresQuery from './postgres_query'; import PostgresQuery from './postgres_query';
import sqlPart from './sql_part'; import sqlPart from './sql_part';
import { auto, IQService } from 'angular'; import { auto } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { CoreEvents } from 'app/types'; import { CoreEvents } from 'app/types';
import { PanelEvents } from '@grafana/data'; import { PanelEvents } from '@grafana/data';
@@ -48,7 +48,6 @@ export class PostgresQueryCtrl extends QueryCtrl {
$scope: any, $scope: any,
$injector: auto.IInjectorService, $injector: auto.IInjectorService,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private $q: IQService,
private uiSegmentSrv: any private uiSegmentSrv: any
) { ) {
super($scope, $injector); super($scope, $injector);
@@ -248,7 +247,7 @@ export class PostgresQueryCtrl extends QueryCtrl {
} }
}); });
this.$q.all([task1, task2]).then(() => { Promise.all([task1, task2]).then(() => {
this.updateRawSqlAndRefresh(); this.updateRawSqlAndRefresh();
}); });
} }
@@ -481,7 +480,7 @@ export class PostgresQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -505,7 +504,7 @@ export class PostgresQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -568,7 +567,7 @@ export class PostgresQueryCtrl extends QueryCtrl {
case 'right': case 'right':
if (['int4', 'int8', 'float4', 'float8', 'timestamp', 'timestamptz'].indexOf(part.datatype) > -1) { if (['int4', 'int8', 'float4', 'float8', 'timestamp', 'timestamptz'].indexOf(part.datatype) > -1) {
// don't do value lookups for numerical fields // don't do value lookups for numerical fields
return this.$q.when([]); return Promise.resolve([]);
} else { } else {
return this.datasource return this.datasource
.metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0])) .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
@@ -583,9 +582,9 @@ export class PostgresQueryCtrl extends QueryCtrl {
.catch(this.handleQueryError.bind(this)); .catch(this.handleQueryError.bind(this));
} }
case 'op': case 'op':
return this.$q.when(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype))); return Promise.resolve(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype)));
default: default:
return this.$q.when([]); return Promise.resolve([]);
} }
} }
case 'part-param-changed': { case 'part-param-changed': {
@@ -606,7 +605,7 @@ export class PostgresQueryCtrl extends QueryCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
return this.$q.when([{ text: 'Remove', value: 'remove-part' }]); return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
} }
} }
} }
@@ -619,7 +618,7 @@ export class PostgresQueryCtrl extends QueryCtrl {
options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' })); options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
} }
options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' })); options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
return this.$q.when(options); return Promise.resolve(options);
} }
addWhereAction(part: any, index: any) { addWhereAction(part: any, index: any) {

View File

@@ -1,9 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import { IQService } from 'angular';
export default class ResponseParser { export default class ResponseParser {
constructor(private $q: IQService) {}
processQueryResult(res: any) { processQueryResult(res: any) {
const data: any[] = []; const data: any[] = [];
@@ -125,7 +122,7 @@ export default class ResponseParser {
} }
if (timeColumnIndex === -1) { if (timeColumnIndex === -1) {
return this.$q.reject({ return Promise.reject({
message: 'Missing mandatory time column in annotation query.', message: 'Missing mandatory time column in annotation query.',
}); });
} }

View File

@@ -2,7 +2,6 @@ import { PostgresDatasource } from '../datasource';
import { CustomVariable } from 'app/features/templating/custom_variable'; import { CustomVariable } from 'app/features/templating/custom_variable';
import { dateTime, toUtc } from '@grafana/data'; import { dateTime, toUtc } from '@grafana/data';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { IQService } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
describe('PostgreSQLDatasource', () => { describe('PostgreSQLDatasource', () => {
@@ -26,13 +25,7 @@ describe('PostgreSQLDatasource', () => {
} as any; } as any;
beforeEach(() => { beforeEach(() => {
ctx.ds = new PostgresDatasource( ctx.ds = new PostgresDatasource(instanceSettings, backendSrv as BackendSrv, templateSrv, ctx.timeSrvMock);
instanceSettings,
backendSrv as BackendSrv,
{} as IQService,
templateSrv,
ctx.timeSrvMock
);
}); });
describe('When performing annotationQuery', () => { describe('When performing annotationQuery', () => {

View File

@@ -145,8 +145,7 @@ export class ColumnOptionsCtrl {
} }
} }
/** @ngInject */ export function columnOptionsTab(uiSegmentSrv: any) {
export function columnOptionsTab($q: any, uiSegmentSrv: any) {
'use strict'; 'use strict';
return { return {
restrict: 'E', restrict: 'E',

View File

@@ -1,6 +1,5 @@
import _ from 'lodash'; import _ from 'lodash';
import { transformers } from './transformers'; import { transformers } from './transformers';
import { IQService } from 'angular';
import { Column } from 'react-virtualized'; import { Column } from 'react-virtualized';
export class TablePanelEditorCtrl { export class TablePanelEditorCtrl {
@@ -14,7 +13,7 @@ export class TablePanelEditorCtrl {
columnsHelpMessage: string; columnsHelpMessage: string;
/** @ngInject */ /** @ngInject */
constructor($scope: any, private $q: IQService, private uiSegmentSrv: any) { constructor($scope: any, private uiSegmentSrv: any) {
$scope.editor = this; $scope.editor = this;
this.panelCtrl = $scope.ctrl; this.panelCtrl = $scope.ctrl;
this.panel = this.panelCtrl.panel; this.panel = this.panelCtrl.panel;
@@ -45,11 +44,11 @@ export class TablePanelEditorCtrl {
getColumnOptions() { getColumnOptions() {
if (!this.panelCtrl.dataRaw) { if (!this.panelCtrl.dataRaw) {
return this.$q.when([]); return Promise.resolve([]);
} }
const columns = this.transformers[this.panel.transform].getColumns(this.panelCtrl.dataRaw); const columns = this.transformers[this.panel.transform].getColumns(this.panelCtrl.dataRaw);
const segments = _.map(columns, (c: any) => this.uiSegmentSrv.newSegment({ value: c.text })); const segments = _.map(columns, (c: any) => this.uiSegmentSrv.newSegment({ value: c.text }));
return this.$q.when(segments); return Promise.resolve(segments);
} }
addColumn() { addColumn() {
@@ -86,8 +85,7 @@ export class TablePanelEditorCtrl {
} }
} }
/** @ngInject */ export function tablePanelEditor(uiSegmentSrv: any) {
export function tablePanelEditor($q: IQService, uiSegmentSrv: any) {
'use strict'; 'use strict';
return { return {
restrict: 'E', restrict: 'E',

View File

@@ -47,67 +47,61 @@ export function ControllerTestContext(this: any) {
}; };
this.createPanelController = (Ctrl: any) => { this.createPanelController = (Ctrl: any) => {
return angularMocks.inject( return angularMocks.inject(($controller: any, $rootScope: GrafanaRootScope, $location: any, $browser: any) => {
($controller: any, $rootScope: GrafanaRootScope, $q: any, $location: any, $browser: any) => { self.scope = $rootScope.$new();
self.scope = $rootScope.$new(); self.$location = $location;
self.$location = $location; self.$browser = $browser;
self.$browser = $browser; self.panel = new PanelModel({ type: 'test' });
self.$q = $q; self.dashboard = { meta: {} };
self.panel = new PanelModel({ type: 'test' }); self.isUtc = false;
self.dashboard = { meta: {} }; self.dashboard.isTimezoneUtc = () => {
self.isUtc = false; return self.isUtc;
self.dashboard.isTimezoneUtc = () => { };
return self.isUtc;
};
$rootScope.appEvent = sinon.spy(); $rootScope.appEvent = sinon.spy();
$rootScope.onAppEvent = sinon.spy(); $rootScope.onAppEvent = sinon.spy();
$rootScope.colors = []; $rootScope.colors = [];
for (let i = 0; i < 50; i++) { for (let i = 0; i < 50; i++) {
$rootScope.colors.push('#' + i); $rootScope.colors.push('#' + i);
}
config.panels['test'] = { info: {} } as PanelPluginMeta;
self.ctrl = $controller(
Ctrl,
{ $scope: self.scope },
{
panel: self.panel,
dashboard: self.dashboard,
}
);
} }
);
config.panels['test'] = { info: {} } as PanelPluginMeta;
self.ctrl = $controller(
Ctrl,
{ $scope: self.scope },
{
panel: self.panel,
dashboard: self.dashboard,
}
);
});
}; };
this.createControllerPhase = (controllerName: string) => { this.createControllerPhase = (controllerName: string) => {
return angularMocks.inject( return angularMocks.inject(($controller: any, $rootScope: GrafanaRootScope, $location: any, $browser: any) => {
($controller: any, $rootScope: GrafanaRootScope, $q: any, $location: any, $browser: any) => { self.scope = $rootScope.$new();
self.scope = $rootScope.$new(); self.$location = $location;
self.$location = $location; self.$browser = $browser;
self.$browser = $browser; self.scope.contextSrv = {};
self.scope.contextSrv = {}; self.scope.panel = {};
self.scope.panel = {}; self.scope.dashboard = { meta: {} };
self.scope.dashboard = { meta: {} }; self.scope.dashboardMeta = {};
self.scope.dashboardMeta = {}; self.scope.dashboardViewState = DashboardViewStateStub();
self.scope.dashboardViewState = DashboardViewStateStub(); self.scope.appEvent = sinon.spy();
self.scope.appEvent = sinon.spy(); self.scope.onAppEvent = sinon.spy();
self.scope.onAppEvent = sinon.spy();
$rootScope.colors = []; $rootScope.colors = [];
for (let i = 0; i < 50; i++) { for (let i = 0; i < 50; i++) {
$rootScope.colors.push('#' + i); $rootScope.colors.push('#' + i);
}
self.$q = $q;
self.scope.skipDataOnInit = true;
self.scope.skipAutoInit = true;
self.controller = $controller(controllerName, {
$scope: self.scope,
});
} }
);
self.scope.skipDataOnInit = true;
self.scope.skipAutoInit = true;
self.controller = $controller(controllerName, {
$scope: self.scope,
});
});
}; };
this.setIsUtc = (isUtc: any = false) => { this.setIsUtc = (isUtc: any = false) => {
@@ -134,8 +128,7 @@ export function ServiceTestContext(this: any) {
this.createService = (name: string) => { this.createService = (name: string) => {
// @ts-ignore // @ts-ignore
return angularMocks.inject( return angularMocks.inject(
($q: any, $rootScope: GrafanaRootScope, $httpBackend: any, $injector: any, $location: any, $timeout: any) => { ($rootScope: GrafanaRootScope, $httpBackend: any, $injector: any, $location: any, $timeout: any) => {
self.$q = $q;
self.$rootScope = $rootScope; self.$rootScope = $rootScope;
self.$httpBackend = $httpBackend; self.$httpBackend = $httpBackend;
self.$location = $location; self.$location = $location;