Browse Source

wip: typings

Torkel Ödegaard 7 years ago
parent
commit
98fabfae3e

+ 3 - 3
packages/grafana-ui/src/types/datasource.ts

@@ -8,14 +8,14 @@ export interface DataQueryResponse {
 
 export interface DataQuery {
   refId: string;
-  [key: string]: any;
+  hide?: boolean;
 }
 
-export interface DataQueryOptions {
+export interface DataQueryOptions<TQuery extends DataQuery = DataQuery> {
   timezone: string;
   range: TimeRange;
   rangeRaw: RawTimeRange;
-  targets: DataQuery[];
+  targets: TQuery[];
   panelId: number;
   dashboardId: number;
   cacheTimeout?: string;

+ 11 - 10
packages/grafana-ui/src/types/plugin.ts

@@ -2,10 +2,11 @@ import { ComponentClass } from 'react';
 import { PanelProps, PanelOptionsProps } from './panel';
 import { DataQueryOptions, DataQuery, DataQueryResponse, QueryHint } from './datasource';
 
-export interface DataSourceApi {
-  name: string;
-  meta: PluginMeta;
-  pluginExports: PluginExports;
+export interface DataSourceApi<TQuery extends DataQuery = DataQuery> {
+  // set externally by grafana
+  name?: string;
+  meta?: PluginMeta;
+  pluginExports?: PluginExports;
 
   /**
    *  min interval range
@@ -15,7 +16,7 @@ export interface DataSourceApi {
   /**
    * Imports queries from a different datasource
    */
-  importQueries?(queries: DataQuery[], originMeta: PluginMeta): Promise<DataQuery[]>;
+  importQueries?(queries: TQuery[], originMeta: PluginMeta): Promise<TQuery[]>;
 
   /**
    * Initializes a datasource after instantiation
@@ -25,7 +26,7 @@ export interface DataSourceApi {
   /**
    * Main metrics / data query action
    */
-  query(options: DataQueryOptions): Promise<DataQueryResponse>;
+  query(options: DataQueryOptions<TQuery>): Promise<DataQueryResponse>;
 
   /**
    * Test & verify datasource settings & connection details
@@ -35,12 +36,12 @@ export interface DataSourceApi {
   /**
    *  Get hints for query improvements
    */
-  getQueryHints(query: DataQuery, results: any[], ...rest: any): QueryHint[];
+  getQueryHints?(query: TQuery, results: any[], ...rest: any): QueryHint[];
 }
 
-export interface QueryEditorProps {
-  datasource: DataSourceApi;
-  query: DataQuery;
+export interface QueryEditorProps<DSType extends DataSourceApi = DataSourceApi, TQuery extends DataQuery = DataQuery> {
+  datasource: DSType;
+  query: TQuery;
   onExecuteQuery?: () => void;
   onQueryChange?: (value: DataQuery) => void;
 }

+ 14 - 0
public/app/features/.all.ts@neomake_22624_74.ts

@@ -0,0 +1,14 @@
+import './annotations/all';
+import './templating/all';
+import './plugins/all';
+import './dashboard/all';
+import './playlist/all';
+import './panel/all';
+import './org/all';
+import './admin';
+import './alerting/NotificationsEditCtrl';
+import './alerting/NotificationsListCtrl';
+import './manage-dashboards';
+import './teams/CreateTeamCtrl';
+import './profile/all';
+import './datasources/settings/dsHttpSettings';

+ 4 - 4
public/app/plugins/datasource/prometheus/components/PromQueryField.tsx

@@ -11,7 +11,7 @@ import { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/
 import BracesPlugin from 'app/features/explore/slate-plugins/braces';
 import RunnerPlugin from 'app/features/explore/slate-plugins/runner';
 import QueryField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField';
-import { DataQuery } from '@grafana/ui/src/types';
+import { PromQuery } from '../types';
 
 const HISTOGRAM_GROUP = '__histograms__';
 const METRIC_MARK = 'metric';
@@ -88,13 +88,13 @@ interface CascaderOption {
 interface PromQueryFieldProps {
   datasource: any;
   error?: string | JSX.Element;
-  initialQuery: DataQuery;
+  initialQuery: PromQuery;
   hint?: any;
   history?: any[];
   metricsByPrefix?: CascaderOption[];
   onClickHintFix?: (action: any) => void;
   onPressEnter?: () => void;
-  onQueryChange?: (value: DataQuery, override?: boolean) => void;
+  onQueryChange?: (value: PromQuery, override?: boolean) => void;
 }
 
 interface PromQueryFieldState {
@@ -166,7 +166,7 @@ class PromQueryField extends React.PureComponent<PromQueryFieldProps, PromQueryF
     // Send text change to parent
     const { initialQuery, onQueryChange } = this.props;
     if (onQueryChange) {
-      const query: DataQuery = {
+      const query: PromQuery = {
         ...initialQuery,
         expr: value,
       };

+ 49 - 45
public/app/plugins/datasource/prometheus/datasource.ts

@@ -1,57 +1,24 @@
+// Libraries
 import _ from 'lodash';
-
 import $ from 'jquery';
+
+// Services & Utils
 import kbn from 'app/core/utils/kbn';
 import * as dateMath from 'app/core/utils/datemath';
 import PrometheusMetricFindQuery from './metric_find_query';
 import { ResultTransformer } from './result_transformer';
 import PrometheusLanguageProvider from './language_provider';
 import { BackendSrv } from 'app/core/services/backend_srv';
-
 import addLabelToQuery from './add_label_to_query';
 import { getQueryHints } from './query_hints';
 import { expandRecordingRules } from './language_utils';
-import { DataQuery } from '@grafana/ui/src/types';
-import { ExploreUrlState } from 'app/types/explore';
-
-export function alignRange(start, end, step) {
-  const alignedEnd = Math.ceil(end / step) * step;
-  const alignedStart = Math.floor(start / step) * step;
-  return {
-    end: alignedEnd,
-    start: alignedStart,
-  };
-}
 
-export function extractRuleMappingFromGroups(groups: any[]) {
-  return groups.reduce(
-    (mapping, group) =>
-      group.rules.filter(rule => rule.type === 'recording').reduce(
-        (acc, rule) => ({
-          ...acc,
-          [rule.name]: rule.query,
-        }),
-        mapping
-      ),
-    {}
-  );
-}
-
-export function prometheusRegularEscape(value) {
-  if (typeof value === 'string') {
-    return value.replace(/'/g, "\\\\'");
-  }
-  return value;
-}
-
-export function prometheusSpecialRegexEscape(value) {
-  if (typeof value === 'string') {
-    return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()]/g, '\\\\$&'));
-  }
-  return value;
-}
+// Types
+import { PromQuery } from './types';
+import { DataQueryOptions, DataSourceApi } from '@grafana/ui/src/types';
+import { ExploreUrlState } from 'app/types/explore';
 
-export class PrometheusDatasource {
+export class PrometheusDatasource implements DataSourceApi<PromQuery> {
   type: string;
   editorSrc: string;
   name: string;
@@ -149,7 +116,7 @@ export class PrometheusDatasource {
     return this.templateSrv.variableExists(target.expr);
   }
 
-  query(options) {
+  query(options: DataQueryOptions<PromQuery>) {
     const start = this.getPrometheusTime(options.range.from, false);
     const end = this.getPrometheusTime(options.range.to, true);
 
@@ -423,7 +390,7 @@ export class PrometheusDatasource {
     });
   }
 
-  getExploreState(queries: DataQuery[]): Partial<ExploreUrlState> {
+  getExploreState(queries: PromQuery[]): Partial<ExploreUrlState> {
     let state: Partial<ExploreUrlState> = { datasource: this.name };
     if (queries && queries.length > 0) {
       const expandedQueries = queries.map(query => ({
@@ -438,7 +405,7 @@ export class PrometheusDatasource {
     return state;
   }
 
-  getQueryHints(query: DataQuery, result: any[]) {
+  getQueryHints(query: PromQuery, result: any[]) {
     return getQueryHints(query.expr || '', result, this);
   }
 
@@ -457,7 +424,7 @@ export class PrometheusDatasource {
       });
   }
 
-  modifyQuery(query: DataQuery, action: any): DataQuery {
+  modifyQuery(query: PromQuery, action: any): PromQuery {
     let expression = query.expr || '';
     switch (action.type) {
       case 'ADD_FILTER': {
@@ -507,3 +474,40 @@ export class PrometheusDatasource {
     return this.resultTransformer.getOriginalMetricName(labelData);
   }
 }
+
+export function alignRange(start, end, step) {
+  const alignedEnd = Math.ceil(end / step) * step;
+  const alignedStart = Math.floor(start / step) * step;
+  return {
+    end: alignedEnd,
+    start: alignedStart,
+  };
+}
+
+export function extractRuleMappingFromGroups(groups: any[]) {
+  return groups.reduce(
+    (mapping, group) =>
+      group.rules.filter(rule => rule.type === 'recording').reduce(
+        (acc, rule) => ({
+          ...acc,
+          [rule.name]: rule.query,
+        }),
+        mapping
+      ),
+    {}
+  );
+}
+
+export function prometheusRegularEscape(value) {
+  if (typeof value === 'string') {
+    return value.replace(/'/g, "\\\\'");
+  }
+  return value;
+}
+
+export function prometheusSpecialRegexEscape(value) {
+  if (typeof value === 'string') {
+    return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()]/g, '\\\\$&'));
+  }
+  return value;
+}

+ 6 - 0
public/app/plugins/datasource/prometheus/types.ts

@@ -0,0 +1,6 @@
+import { DataQuery } from '@grafana/ui/src/types';
+
+export interface PromQuery extends DataQuery {
+  expr: string;
+}
+

+ 5 - 6
public/app/plugins/datasource/testdata/QueryEditor.tsx

@@ -10,18 +10,17 @@ import { FormLabel, Select, SelectOptionItem } from '@grafana/ui';
 
 // Types
 import { QueryEditorProps } from '@grafana/ui/src/types';
-
-interface Scenario {
-  id: string;
-  name: string;
-}
+import { TestDataDatasource } from './datasource';
+import { TestDataQuery, Scenario } from './types';
 
 interface State {
   scenarioList: Scenario[];
   current: Scenario | null;
 }
 
-export class QueryEditor extends PureComponent<QueryEditorProps> {
+type Props = QueryEditorProps<TestDataDatasource, TestDataQuery>;
+
+export class QueryEditor extends PureComponent<Props> {
   backendSrv: BackendSrv = getBackendSrv();
 
   state: State = {

+ 5 - 4
public/app/plugins/datasource/testdata/datasource.ts

@@ -1,15 +1,17 @@
 import _ from 'lodash';
 import TableModel from 'app/core/table_model';
+import { DataSourceApi, DataQueryOptions } from '@grafana/ui';
+import { TestDataQuery } from './types';
 
-class TestDataDatasource {
-  id: any;
+export class TestDataDatasource implements DataSourceApi<TestDataQuery> {
+  id: number;
 
   /** @ngInject */
   constructor(instanceSettings, private backendSrv, private $q) {
     this.id = instanceSettings.id;
   }
 
-  query(options) {
+  query(options: DataQueryOptions<TestDataQuery>) {
     const queries = _.filter(options.targets, item => {
       return item.hide !== true;
     }).map(item => {
@@ -93,4 +95,3 @@ class TestDataDatasource {
   }
 }
 
-export { TestDataDatasource };

+ 4 - 4
public/app/plugins/datasource/testdata/module.ts

@@ -1,6 +1,6 @@
 import { TestDataDatasource } from './datasource';
-import { TestDataQueryCtrl } from './query_ctrl';
-// import { QueryEditor } from './QueryEditor';
+// import { TestDataQueryCtrl } from './query_ctrl';
+import { QueryEditor } from './QueryEditor';
 
 class TestDataAnnotationsQueryCtrl {
   annotation: any;
@@ -11,8 +11,8 @@ class TestDataAnnotationsQueryCtrl {
 }
 
 export {
-  // QueryEditor,
+  QueryEditor,
   TestDataDatasource as Datasource,
-  TestDataQueryCtrl as QueryCtrl,
+  // TestDataQueryCtrl as QueryCtrl,
   TestDataAnnotationsQueryCtrl as AnnotationsQueryCtrl,
 };

+ 11 - 0
public/app/plugins/datasource/testdata/types.ts

@@ -0,0 +1,11 @@
+import { DataQuery } from '@grafana/ui/src/types';
+
+export interface TestDataQuery extends DataQuery {
+  scenarioId: string;
+}
+
+export interface Scenario {
+  id: string;
+  name: string;
+}
+