ValueMapping: handle multiple regex mappings (#41515)

This commit is contained in:
Jim McDonald 2021-11-10 07:31:44 +00:00 committed by GitHub
parent 57adbc3bd6
commit 11646b41fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 7 deletions

View File

@ -52,6 +52,23 @@ const testSet1: ValueMapping[] = [
},
];
const testSet2: ValueMapping[] = [
{
type: MappingType.RegexToText,
options: {
pattern: '^([^.]*).foo.com$',
result: { text: 'Hostname $1' },
},
},
{
type: MappingType.RegexToText,
options: {
pattern: '^([^.]*).bar.com$',
result: { text: 'Hostname $1' },
},
},
];
describe('Format value with value mappings', () => {
it('should return null with no valuemappings', () => {
const valueMappings: ValueMapping[] = [];
@ -132,6 +149,23 @@ describe('Format value with value mappings', () => {
});
});
describe('Format value with regex mappings', () => {
it('should return correct regular expression result', () => {
const value = 'www.foo.com';
expect(getValueMappingResult(testSet2, value)).toEqual({ text: 'Hostname www' });
});
it('should return correct regular expression result on second regex', () => {
const value = 'ftp.bar.com';
expect(getValueMappingResult(testSet2, value)).toEqual({ text: 'Hostname ftp' });
});
it('should return null with unmatched value', () => {
const value = 'www.baz.com';
expect(getValueMappingResult(testSet2, value)).toBeNull();
});
});
describe('isNumeric', () => {
it.each`
value | expected

View File

@ -1,4 +1,12 @@
import { MappingType, SpecialValueMatch, ThresholdsConfig, ValueMap, ValueMapping, ValueMappingResult } from '../types';
import {
MappingType,
SpecialValueMatch,
ThresholdsConfig,
ValueMap,
ValueMapping,
ValueMappingResult,
SpecialValueOptions,
} from '../types';
import { getActiveThreshold } from '../field';
import { stringToJsRegex } from '../text/string';
@ -41,22 +49,22 @@ export function getValueMappingResult(valueMappings: ValueMapping[], value: any)
case MappingType.RegexToText:
if (value == null) {
console.log('null value');
continue;
}
if (typeof value !== 'string') {
console.log('non-string value', typeof value);
continue;
}
const regex = stringToJsRegex(vm.options.pattern);
const thisResult = Object.create(vm.options.result);
thisResult.text = value.replace(regex, vm.options.result.text || '');
return thisResult;
if (value.match(regex)) {
const thisResult = Object.create(vm.options.result);
thisResult.text = value.replace(regex, vm.options.result.text || '');
return thisResult;
}
case MappingType.SpecialValue:
switch (vm.options.match) {
switch ((vm.options as SpecialValueOptions).match) {
case SpecialValueMatch.Null: {
if (value == null) {
return vm.options.result;