Skip to content

Commit

Permalink
refactor: 💡 convert Interpreter .js -> .ts (elastic#44545) (elastic#4…
Browse files Browse the repository at this point in the history
…7190)

* refactor: 💡 convert Interpreter .js -> .ts

* fix: 🐛 fix TypeScript type errors

* test: 💍 remove old snapshot
  • Loading branch information
streamich committed Oct 3, 2019
1 parent ace757c commit 342fea5
Show file tree
Hide file tree
Showing 23 changed files with 118 additions and 105 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ import { font } from '../font';
import { functionWrapper } from '../../../test_helpers';

describe('font', () => {
const fn = functionWrapper(font);
const fn: any = functionWrapper(font);

describe('default output', () => {
const result = fn(null);

it('returns a style', () => {
expect(result)
(expect as any)(result)
.to.have.property('type', 'style')
.and.to.have.property('spec')
.and.to.have.property('css');
Expand All @@ -40,8 +40,8 @@ describe('font', () => {
describe('size', () => {
it('sets font size', () => {
const result = fn(null, { size: 20 });
expect(result.spec).to.have.property('fontSize', '20px');
expect(result.css).to.contain('font-size:20px');
(expect as any)(result.spec).to.have.property('fontSize', '20px');
(expect as any)(result.css).to.contain('font-size:20px');
});

it('defaults to 14px', () => {
Expand Down Expand Up @@ -110,7 +110,7 @@ describe('font', () => {
expect(result.css).to.contain('font-weight:400');
});

it('defaults to \'normal\'', () => {
it("defaults to 'normal'", () => {
const result = fn(null);
expect(result.spec).to.have.property('fontWeight', 'normal');
expect(result.css).to.contain('font-weight:normal');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
export const clog = () => ({
name: 'clog',
help: 'Outputs the context to the console',
fn: context => {
console.log(context); //eslint-disable-line no-console
fn: (context: any) => {
console.log(context); // eslint-disable-line no-console
return context;
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,12 @@ import { visualization } from './visualization';
import { visDimension } from './vis_dimension';

export const functions = [
clog, esaggs, font, kibana, kibanaContext, range, visualization, visDimension,
clog,
esaggs,
font,
kibana,
kibanaContext,
range,
visualization,
visDimension,
];
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import { kibana } from './kibana';

describe('interpreter/functions#kibana', () => {
const fn = functionWrapper(kibana);
let context;
let initialContext;
let handlers;
let context: any;
let initialContext: any;
let handlers: any;

beforeEach(() => {
context = { timeRange: { from: '0', to: '1' } };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ export const kibana = () => ({
type: 'kibana_context',
context: {},
help: i18n.translate('interpreter.functions.kibana.help', {
defaultMessage: 'Gets kibana global context'
defaultMessage: 'Gets kibana global context',
}),
args: {},
fn(context, args, handlers) {
fn(context: any, args: any, handlers: any) {
const initialContext = handlers.getInitialContext ? handlers.getInitialContext() : {};

if (context.query) {
Expand All @@ -45,7 +45,7 @@ export const kibana = () => ({
type: 'kibana_context',
query: initialContext.query,
filters: initialContext.filters,
timeRange: timeRange,
timeRange,
};
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,10 @@ export const kibanaContext = () => ({
name: 'kibana_context',
type: 'kibana_context',
context: {
types: [
'kibana_context',
'null',
],
types: ['kibana_context', 'null'],
},
help: i18n.translate('interpreter.functions.kibana_context.help', {
defaultMessage: 'Updates kibana global context'
defaultMessage: 'Updates kibana global context',
}),
args: {
q: {
Expand All @@ -49,11 +46,11 @@ export const kibanaContext = () => ({
savedSearchId: {
types: ['string', 'null'],
default: null,
}
},
},
async fn(context, args) {
async fn(context: any, args: any) {
const $injector = await chrome.dangerouslyGetActiveInjector();
const savedSearches = $injector.get('savedSearches');
const savedSearches = $injector.get('savedSearches') as any;
const queryArg = args.q ? JSON.parse(args.q) : [];
let queries = Array.isArray(queryArg) ? queryArg : [queryArg];
let filters = args.filters ? JSON.parse(args.filters) : [];
Expand All @@ -71,16 +68,16 @@ export const kibanaContext = () => ({
}

if (context.filters) {
filters = filters.concat(context.filters).filter(f => !f.meta.disabled);
filters = filters.concat(context.filters).filter((f: any) => !f.meta.disabled);
}

const timeRange = args.timeRange ? JSON.parse(args.timeRange) : context.timeRange;

return {
type: 'kibana_context',
query: queries,
filters: filters,
timeRange: timeRange,
filters,
timeRange,
};
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,48 +22,48 @@ import { i18n } from '@kbn/i18n';
export const visDimension = () => ({
name: 'visdimension',
help: i18n.translate('interpreter.function.visDimension.help', {
defaultMessage: 'Generates visConfig dimension object'
defaultMessage: 'Generates visConfig dimension object',
}),
type: 'vis_dimension',
context: {
types: [
'kibana_datatable'
],
types: ['kibana_datatable'],
},
args: {
accessor: {
types: ['string', 'number'],
aliases: ['_'],
help: i18n.translate('interpreter.function.visDimension.accessor.help', {
defaultMessage: 'Column in your dataset to use (either column index or column name)'
defaultMessage: 'Column in your dataset to use (either column index or column name)',
}),
},
format: {
types: ['string'],
default: 'string'
default: 'string',
},
formatParams: {
types: ['string'],
default: '"{}"',
}
},
},
fn: (context, args) => {
const accessor = Number.isInteger(args.accessor) ?
args.accessor :
context.columns.find(c => c.id === args.accessor);
fn: (context: any, args: any) => {
const accessor = Number.isInteger(args.accessor)
? args.accessor
: context.columns.find((c: any) => c.id === args.accessor);
if (accessor === undefined) {
throw new Error(i18n.translate('interpreter.function.visDimension.error.accessor', {
defaultMessage: 'Column name provided is invalid'
}));
throw new Error(
i18n.translate('interpreter.function.visDimension.error.accessor', {
defaultMessage: 'Column name provided is invalid',
})
);
}

return {
type: 'vis_dimension',
accessor: accessor,
accessor,
format: {
id: args.format,
params: JSON.parse(args.formatParams),
}
},
};
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,16 @@
import { get } from 'lodash';
import { i18n } from '@kbn/i18n';
import chrome from 'ui/chrome';
import { setup as data } from '../../../data/public/legacy';
import { start as visualizations } from '../../../visualizations/public/legacy';

import { FilterBarQueryFilterProvider } from 'ui/filter_manager/query_filter';
import { PersistedState } from 'ui/persisted_state';
import { setup as data } from '../../../data/public/legacy';
import { start as visualizations } from '../../../visualizations/public/legacy';

export const visualization = () => ({
name: 'visualization',
type: 'render',
help: i18n.translate('interpreter.functions.visualization.help', {
defaultMessage: 'A simple visualization'
defaultMessage: 'A simple visualization',
}),
args: {
index: {
Expand Down Expand Up @@ -60,17 +59,17 @@ export const visualization = () => ({
uiState: {
types: ['string'],
default: '"{}"',
}
},
},
async fn(context, args, handlers) {
async fn(context: any, args: any, handlers: any) {
const $injector = await chrome.dangerouslyGetActiveInjector();
const Private = $injector.get('Private');
const Private = $injector.get('Private') as any;
const { indexPatterns } = data.indexPatterns;
const queryFilter = Private(FilterBarQueryFilterProvider);

const visConfigParams = JSON.parse(args.visConfig);
const schemas = JSON.parse(args.schemas);
const visType = visualizations.types.get(args.type || 'histogram');
const visType = visualizations.types.get(args.type || 'histogram') as any;
const indexPattern = args.index ? await indexPatterns.get(args.index) : null;

const uiStateParams = JSON.parse(args.uiState);
Expand All @@ -85,7 +84,7 @@ export const visualization = () => ({
timeRange: get(context, 'timeRange', null),
query: get(context, 'query', null),
filters: get(context, 'filters', null),
uiState: uiState,
uiState,
inspectorAdapters: handlers.inspectorAdapters,
queryFilter,
forceFetch: true,
Expand All @@ -95,14 +94,14 @@ export const visualization = () => ({
if (typeof visType.responseHandler === 'function') {
if (context.columns) {
// assign schemas to aggConfigs
context.columns.forEach(column => {
context.columns.forEach((column: any) => {
if (column.aggConfig) {
column.aggConfig.aggConfigs.schemas = visType.schemas.all;
}
});

Object.keys(schemas).forEach(key => {
schemas[key].forEach(i => {
schemas[key].forEach((i: any) => {
if (context.columns[i] && context.columns[i].aggConfig) {
context.columns[i].aggConfig.schema = key;
}
Expand All @@ -119,8 +118,8 @@ export const visualization = () => ({
value: {
visData: context,
visType: args.type,
visConfig: visConfigParams
}
visConfig: visConfigParams,
},
};
}
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ jest.mock('ui/new_platform', () => ({
injectedMetadata: {
getKibanaVersion: () => '8.0.0',
getBasePath: () => '/lol',
}
}
}
},
},
},
}));
jest.mock('uiExports/interpreter');

Expand All @@ -38,7 +38,7 @@ jest.mock('@kbn/interpreter/common', () => ({
const mockInterpreter = {
interpreter: {
interpretAst: jest.fn(),
}
},
};
jest.mock('./lib/interpreter', () => ({
initializeInterpreter: jest.fn().mockReturnValue(Promise.resolve(mockInterpreter)),
Expand All @@ -57,9 +57,9 @@ jest.mock('./functions', () => ({ functions: [{}, {}, {}] }));
jest.mock('./renderers/visualization', () => ({ visualization: {} }));

describe('interpreter/interpreter', () => {
let getInterpreter;
let interpretAst;
let initializeInterpreter;
let getInterpreter: any;
let interpretAst: any;
let initializeInterpreter: any;

beforeEach(() => {
jest.clearAllMocks();
Expand Down Expand Up @@ -117,5 +117,4 @@ describe('interpreter/interpreter', () => {
expect(mockInterpreter.interpreter.interpretAst).toHaveBeenCalledTimes(2);
});
});

});
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

import 'uiExports/interpreter';
// @ts-ignore
import { register, registryFactory } from '@kbn/interpreter/common';
import { initializeInterpreter } from './lib/interpreter';
import { registries } from './registries';
Expand All @@ -27,15 +28,18 @@ import { typeSpecs } from '../../../../plugins/expressions/common';

// Expose kbnInterpreter.register(specs) and kbnInterpreter.registries() globally so that plugins
// can register without a transpile step.
global.kbnInterpreter = Object.assign(global.kbnInterpreter || {}, registryFactory(registries));
(global as any).kbnInterpreter = Object.assign(
(global as any).kbnInterpreter || {},
registryFactory(registries)
);

register(registries, {
types: typeSpecs,
browserFunctions: functions,
renderers: [visualization],
});

let interpreterPromise;
let interpreterPromise: Promise<any> | undefined;

export const getInterpreter = async () => {
if (!interpreterPromise) {
Expand All @@ -44,7 +48,7 @@ export const getInterpreter = async () => {
return await interpreterPromise;
};

export const interpretAst = async (...params) => {
export const interpretAst = async (...params: any) => {
const { interpreter } = await getInterpreter();
return await interpreter.interpretAst(...params);
};
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

export function RenderFunction(config) {
export function RenderFunction(this: any, config: any) {
// This must match the name of the function that is used to create the `type: render` object
this.name = config.name;

Expand All @@ -36,7 +36,7 @@ export function RenderFunction(config) {
// the function called to render the data
this.render =
config.render ||
function render(domNode, data, done) {
function render(domNode: any, data: any, done: any) {
done();
};
}
Loading

0 comments on commit 342fea5

Please sign in to comment.