Skip to content

Commit

Permalink
Make createStream function more readable
Browse files Browse the repository at this point in the history
  • Loading branch information
nchaulet committed Apr 28, 2020
1 parent 792bf79 commit d3933c0
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import { safeLoad } from 'js-yaml';
import { DatasourceConfigRecord } from '../../../../common';

function replaceVariablesInYaml(yamlVariables: { [k: string]: any }, yaml: any) {
const yamlKeys = Object.keys(yamlVariables);
if (yamlKeys.length === 0) {
if (Object.keys(yamlVariables).length === 0) {
return yaml;
}

Expand All @@ -19,15 +18,15 @@ function replaceVariablesInYaml(yamlVariables: { [k: string]: any }, yaml: any)
yaml[key] = replaceVariablesInYaml(yamlVariables, value);
}

if (typeof value === 'string' && yamlKeys.indexOf(value) >= 0) {
if (typeof value === 'string' && value in yamlVariables) {
yaml[key] = yamlVariables[value];
}
});

return yaml;
}

export function createStream(variables: DatasourceConfigRecord, streamTemplate: string) {
function buildTemplateVariables(variables: DatasourceConfigRecord) {
const yamlValues: { [k: string]: any } = {};
const vars = Object.entries(variables).reduce((acc, [key, recordEntry]) => {
// support variables with . like key.patterns
Expand Down Expand Up @@ -56,8 +55,15 @@ export function createStream(variables: DatasourceConfigRecord, streamTemplate:
return acc;
}, {} as { [k: string]: any });

return { vars, yamlValues };
}

export function createStream(variables: DatasourceConfigRecord, streamTemplate: string) {
const { vars, yamlValues } = buildTemplateVariables(variables);

const template = Handlebars.compile(streamTemplate, { noEscape: true });
const stream = template(vars);

const yamlFromStream = safeLoad(stream, {});

return replaceVariablesInYaml(yamlValues, yamlFromStream);
Expand Down

0 comments on commit d3933c0

Please sign in to comment.