Skip to content

Commit

Permalink
Chore: Fix typescript strict null errors from 674 -> 565 (grafana#26057)
Browse files Browse the repository at this point in the history
* Chore: Fix typescript strict null errors

* Added new limit

* Fixed ts issue

* fixed tests

* trying to fix type inference

* Fixing more ts errors

* Revert tsconfig option

* Fix

* Fixed code

* More fixes

* fix tests

* Updated snapshot
  • Loading branch information
torkelo authored Jul 6, 2020
1 parent 4fc984f commit 7e8bd0c
Show file tree
Hide file tree
Showing 39 changed files with 198 additions and 182 deletions.
16 changes: 3 additions & 13 deletions packages/grafana-data/src/types/datasource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,10 @@ export interface DataSourcePluginOptionsEditorProps<JSONData = DataSourceJsonDat
}

// Utility type to extract the query type TQuery from a class extending DataSourceApi<TQuery, TOptions>
export type DataSourceQueryType<DSType extends DataSourceApi<any, any>> = DSType extends DataSourceApi<
infer TQuery,
infer _TOptions
>
? TQuery
: never;
export type DataSourceQueryType<DSType> = DSType extends DataSourceApi<infer TQuery, any> ? TQuery : never;

// Utility type to extract the options type TOptions from a class extending DataSourceApi<TQuery, TOptions>
export type DataSourceOptionsType<DSType extends DataSourceApi<any, any>> = DSType extends DataSourceApi<
infer _TQuery,
infer TOptions
>
? TOptions
: never;
export type DataSourceOptionsType<DSType> = DSType extends DataSourceApi<any, infer TOptions> ? TOptions : never;

export class DataSourcePlugin<
DSType extends DataSourceApi<TQuery, TOptions>,
Expand Down Expand Up @@ -453,7 +443,6 @@ export interface DataQueryTimings {
}

export interface QueryFix {
type: string;
label: string;
action?: QueryFixAction;
}
Expand All @@ -472,6 +461,7 @@ export interface QueryHint {

export interface MetricFindValue {
text: string;
expandable?: boolean;
}

export interface DataSourceJsonData {
Expand Down
2 changes: 1 addition & 1 deletion public/app/core/utils/kbn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ kbn.interval_to_ms = (str: string) => {
return info.sec * 1000 * info.count;
};

kbn.interval_to_seconds = (str: string) => {
kbn.interval_to_seconds = (str: string): number => {
const info = kbn.describe_interval(str);
return info.sec * info.count;
};
Expand Down
4 changes: 2 additions & 2 deletions public/app/features/dashboard/state/PanelQueryRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export interface GetDataOptions {
}

export class PanelQueryRunner {
private subject?: ReplaySubject<PanelData>;
private subject: ReplaySubject<PanelData>;
private subscription?: Unsubscribable;
private lastResult?: PanelData;
private dataConfigSource: DataConfigSource;
Expand Down Expand Up @@ -244,7 +244,7 @@ export class PanelQueryRunner {
}
}

getLastResult(): PanelData {
getLastResult(): PanelData | undefined {
return this.lastResult;
}
}
Expand Down
4 changes: 2 additions & 2 deletions public/app/features/templating/template_srv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,9 +265,9 @@ export class TemplateSrv implements BaseTemplateSrv {
return variableName;
}

variableExists(expression: string) {
variableExists(expression: string): boolean {
const name = this.getVariableName(expression);
return name && this.getVariableAtIndex(name) !== void 0;
return (name && this.getVariableAtIndex(name)) !== undefined;
}

highlightVariablesAsHtml(str: string) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ exports[`LokiExploreQueryEditor should render component 1`] = `
},
Symbol(length): 0,
},
"logLabelFetchTs": 0,
"request": [Function],
"seriesCache": LRUCache {
Symbol(max): 10,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ArrayVector, Field, FieldType, LinkModel } from '@grafana/data';
import { getFieldLinksForExplore } from '../../../../features/explore/utils/links';

type Props = {
derivedFields: DerivedFieldConfig[];
derivedFields?: DerivedFieldConfig[];
className?: string;
};
export const DebugSection = (props: Props) => {
Expand Down Expand Up @@ -92,7 +92,7 @@ function makeDebugFields(derivedFields: DerivedFieldConfig[], debugText: string)
try {
const testMatch = debugText.match(field.matcherRegex);
const value = testMatch && testMatch[1];
let link: LinkModel<Field> = null;
let link: LinkModel<Field> | null = null;

if (field.url && value) {
link = getFieldLinksForExplore(
Expand All @@ -116,7 +116,6 @@ function makeDebugFields(derivedFields: DerivedFieldConfig[], debugText: string)
href: link && link.href,
} as DebugField;
} catch (error) {
console.error(error);
return {
name: field.name,
error,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Props = {
value?: DerivedFieldConfig[];
onChange: (value: DerivedFieldConfig[]) => void;
};

export const DerivedFields = (props: Props) => {
const { value, onChange } = props;
const theme = useTheme();
Expand Down
8 changes: 4 additions & 4 deletions public/app/plugins/datasource/loki/datasource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ export class LokiDatasource extends DataSourceApi<LokiQuery, LokiOptions> {

getTime(date: string | DateTime, roundUp: boolean) {
if (typeof date === 'string') {
date = dateMath.parse(date, roundUp);
date = dateMath.parse(date, roundUp)!;
}

return Math.ceil(date.valueOf() * 1e6);
Expand Down Expand Up @@ -517,9 +517,9 @@ export class LokiDatasource extends DataSourceApi<LokiQuery, LokiOptions> {
return annotations;
}

showContextToggle = (row?: LogRowModel) => {
return row && row.searchWords && row.searchWords.length > 0;
};
showContextToggle(row?: LogRowModel): boolean {
return (row && row.searchWords && row.searchWords.length > 0) === true;
}

throwUnless = (err: any, condition: boolean, target: LokiQuery) => {
if (condition) {
Expand Down
24 changes: 14 additions & 10 deletions public/app/plugins/datasource/loki/language_provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function addHistoryMetadata(item: CompletionItem, history: LokiHistoryIte
export default class LokiLanguageProvider extends LanguageProvider {
labelKeys: string[];
logLabelOptions: any[];
logLabelFetchTs?: number;
logLabelFetchTs: number;
started: boolean;
initialRange: AbsoluteTimeRange;
datasource: LokiDatasource;
Expand All @@ -77,6 +77,7 @@ export default class LokiLanguageProvider extends LanguageProvider {

this.datasource = datasource;
this.labelKeys = [];
this.logLabelFetchTs = 0;

Object.assign(this, initialValues);
}
Expand Down Expand Up @@ -127,6 +128,11 @@ export default class LokiLanguageProvider extends LanguageProvider {
*/
async provideCompletionItems(input: TypeaheadInput, context?: TypeaheadContext): Promise<TypeaheadOutput> {
const { wrapperClasses, value, prefix, text } = input;
const emptyResult: TypeaheadOutput = { suggestions: [] };

if (!value) {
return emptyResult;
}

// Local text properties
const empty = value?.document.text.length === 0;
Expand Down Expand Up @@ -169,18 +175,16 @@ export default class LokiLanguageProvider extends LanguageProvider {
return this.getTermCompletionItems();
}

return {
suggestions: [],
};
return emptyResult;
}

getBeginningCompletionItems = (context: TypeaheadContext): TypeaheadOutput => {
getBeginningCompletionItems = (context?: TypeaheadContext): TypeaheadOutput => {
return {
suggestions: [...this.getEmptyCompletionItems(context).suggestions, ...this.getTermCompletionItems().suggestions],
};
};

getEmptyCompletionItems(context: TypeaheadContext): TypeaheadOutput {
getEmptyCompletionItems(context?: TypeaheadContext): TypeaheadOutput {
const history = context?.history;
const suggestions = [];

Expand Down Expand Up @@ -386,7 +390,7 @@ export default class LokiLanguageProvider extends LanguageProvider {
async fetchLogLabels(absoluteRange: AbsoluteTimeRange): Promise<any> {
const url = '/loki/api/v1/label';
try {
this.logLabelFetchTs = Date.now();
this.logLabelFetchTs = Date.now().valueOf();
const rangeParams = absoluteRange ? rangeToParams(absoluteRange) : {};
const res = await this.request(url, rangeParams);
this.labelKeys = res.slice().sort();
Expand All @@ -398,7 +402,7 @@ export default class LokiLanguageProvider extends LanguageProvider {
}

async refreshLogLabels(absoluteRange: AbsoluteTimeRange, forceRefresh?: boolean) {
if ((this.labelKeys && Date.now() - this.logLabelFetchTs > LABEL_REFRESH_INTERVAL) || forceRefresh) {
if ((this.labelKeys && Date.now().valueOf() - this.logLabelFetchTs > LABEL_REFRESH_INTERVAL) || forceRefresh) {
await this.fetchLogLabels(absoluteRange);
}
}
Expand All @@ -409,7 +413,7 @@ export default class LokiLanguageProvider extends LanguageProvider {
* @param name
*/
fetchSeriesLabels = async (match: string, absoluteRange: AbsoluteTimeRange): Promise<Record<string, string[]>> => {
const rangeParams: { start?: number; end?: number } = absoluteRange ? rangeToParams(absoluteRange) : {};
const rangeParams = absoluteRange ? rangeToParams(absoluteRange) : { start: 0, end: 0 };
const url = '/loki/api/v1/series';
const { start, end } = rangeParams;

Expand Down Expand Up @@ -447,7 +451,7 @@ export default class LokiLanguageProvider extends LanguageProvider {
async fetchLabelValues(key: string, absoluteRange: AbsoluteTimeRange): Promise<string[]> {
const url = `/loki/api/v1/label/${key}/values`;
let values: string[] = [];
const rangeParams: { start?: number; end?: number } = absoluteRange ? rangeToParams(absoluteRange) : {};
const rangeParams = absoluteRange ? rangeToParams(absoluteRange) : { start: 0, end: 0 };
const { start, end } = rangeParams;

const cacheKey = this.generateCacheKey(url, start, end, key);
Expand Down
2 changes: 1 addition & 1 deletion public/app/plugins/datasource/loki/query_utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('getHighlighterExpressionsFromQuery', () => {
});

it('returns null if filter term is not wrapped in double quotes', () => {
expect(getHighlighterExpressionsFromQuery('{foo="bar"} |= x')).toEqual(null);
expect(getHighlighterExpressionsFromQuery('{foo="bar"} |= x')).toEqual([]);
});

it('escapes filter term if regex filter operator is not used', () => {
Expand Down
6 changes: 4 additions & 2 deletions public/app/plugins/datasource/loki/query_utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import escapeRegExp from 'lodash/escapeRegExp';

export function formatQuery(selector: string): string {
export function formatQuery(selector: string | undefined): string {
return `${selector || ''}`.trim();
}

Expand All @@ -11,6 +11,7 @@ export function formatQuery(selector: string): string {
export function getHighlighterExpressionsFromQuery(input: string): string[] {
let expression = input;
const results = [];

// Consume filter expression from left to right
while (expression) {
const filterStart = expression.search(/\|=|\|~|!=|!~/);
Expand Down Expand Up @@ -43,8 +44,9 @@ export function getHighlighterExpressionsFromQuery(input: string): string[] {
const regexOperator = filterOperator === '|~';
results.push(regexOperator ? unwrappedFilterTerm : escapeRegExp(unwrappedFilterTerm));
} else {
return null;
return [];
}
}

return results;
}
31 changes: 17 additions & 14 deletions public/app/plugins/datasource/loki/result_transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
Field,
QueryResultMetaStat,
QueryResultMeta,
TimeSeriesValue,
} from '@grafana/data';

import templateSrv from 'app/features/templating/template_srv';
Expand Down Expand Up @@ -154,16 +155,14 @@ function lokiMatrixToTimeSeries(matrixResult: LokiMatrixResult, options: Transfo
};
}

function lokiPointsToTimeseriesPoints(
data: Array<[number, string]>,
options: TransformerOptions
): Array<[number, number]> {
function lokiPointsToTimeseriesPoints(data: Array<[number, string]>, options: TransformerOptions): TimeSeriesValue[][] {
const stepMs = options.step * 1000;
const datapoints: Array<[number, number]> = [];
const datapoints: TimeSeriesValue[][] = [];

let baseTimestampMs = options.start / 1e6;
for (const [time, value] of data) {
let datapointValue = parseFloat(value);
let datapointValue: TimeSeriesValue = parseFloat(value);

if (isNaN(datapointValue)) {
datapointValue = null;
}
Expand Down Expand Up @@ -198,7 +197,7 @@ export function lokiResultsToTableModel(

// Collect all labels across all metrics
const metricLabels: Set<string> = new Set<string>(
lokiResults.reduce((acc, cur) => acc.concat(Object.keys(cur.metric)), [])
lokiResults.reduce((acc, cur) => acc.concat(Object.keys(cur.metric)), [] as string[])
);

// Sort metric labels, create columns for them and record their index
Expand Down Expand Up @@ -245,9 +244,9 @@ function createMetricLabel(labelData: { [key: string]: string }, options?: Trans
let label =
options === undefined || _.isEmpty(options.legendFormat)
? getOriginalMetricName(labelData)
: renderTemplate(templateSrv.replace(options.legendFormat), labelData);
: renderTemplate(templateSrv.replace(options.legendFormat ?? ''), labelData);

if (!label) {
if (!label && options) {
label = options.query;
}
return label;
Expand All @@ -272,11 +271,13 @@ export function decamelize(s: string): string {
}

// Turn loki stats { metric: value } into meta stat { title: metric, value: value }
function lokiStatsToMetaStat(stats: LokiStats): QueryResultMetaStat[] {
function lokiStatsToMetaStat(stats: LokiStats | undefined): QueryResultMetaStat[] {
const result: QueryResultMetaStat[] = [];

if (!stats) {
return result;
}

for (const section in stats) {
const values = stats[section];
for (const label in values) {
Expand All @@ -293,6 +294,7 @@ function lokiStatsToMetaStat(stats: LokiStats): QueryResultMetaStat[] {
result.push({ displayName: title, value, unit });
}
}

return result;
}

Expand All @@ -309,6 +311,7 @@ export function lokiStreamsToDataframes(
const custom = {
lokiQueryStatKey: 'Summary: total bytes processed',
};

const series: DataFrame[] = data.map(stream => {
const dataFrame = lokiStreamResultToDataFrame(stream, reverse);
enhanceDataFrame(dataFrame, config);
Expand Down Expand Up @@ -406,10 +409,10 @@ export function rangeQueryResponseToTimeSeries(

const transformerOptions: TransformerOptions = {
format: target.format,
legendFormat: target.legendFormat,
start: query.start,
end: query.end,
step: query.step,
legendFormat: target.legendFormat ?? '',
start: query.start!,
end: query.end!,
step: query.step!,
query: query.query,
responseListLength,
refId: target.refId,
Expand Down
6 changes: 3 additions & 3 deletions public/app/plugins/datasource/loki/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export interface LokiVectorResponse {
}

export interface LokiMatrixResult {
metric: { [label: string]: string };
metric: Record<string, string>;
values: Array<[number, string]>;
}

Expand Down Expand Up @@ -115,8 +115,8 @@ export type DerivedFieldConfig = {
};

export interface TransformerOptions {
format: string;
legendFormat: string;
format?: string;
legendFormat?: string;
step: number;
start: number;
end: number;
Expand Down
5 changes: 4 additions & 1 deletion public/app/plugins/datasource/mixed/MixedDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,17 @@ export class MixedDatasource extends DataSourceApi<DataQuery> {
// Build groups of queries to run in parallel
const sets: { [key: string]: DataQuery[] } = groupBy(queries, 'datasource');
const mixed: BatchedQueries[] = [];

for (const key in sets) {
const targets = sets[key];
const dsName: string | undefined = targets[0].datasource;
const dsName = targets[0].datasource;

mixed.push({
datasource: getDataSourceSrv().get(dsName, request.scopedVars),
targets,
});
}

return this.batchQueries(mixed, request);
}

Expand Down
Loading

0 comments on commit 7e8bd0c

Please sign in to comment.