Skip to content

Commit

Permalink
Update ByteSizeValue to coerce strings to numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
jportner committed Jan 7, 2020
1 parent 056c597 commit 0e8cea9
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 7 deletions.
8 changes: 4 additions & 4 deletions packages/kbn-config-schema/src/byte_size_value/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
import { ByteSizeValue } from '.';

describe('parsing units', () => {
test('number string (bytes)', () => {
expect(ByteSizeValue.parse('123').getValueInBytes()).toBe(123);
});

test('bytes', () => {
expect(ByteSizeValue.parse('123b').getValueInBytes()).toBe(123);
});
Expand All @@ -37,10 +41,6 @@ describe('parsing units', () => {
expect(ByteSizeValue.parse('1gb').getValueInBytes()).toBe(1073741824);
});

test('throws an error when no unit specified', () => {
expect(() => ByteSizeValue.parse('123')).toThrowError('could not parse byte size value');
});

test('throws an error when unsupported unit specified', () => {
expect(() => ByteSizeValue.parse('1tb')).toThrowError('could not parse byte size value');
});
Expand Down
10 changes: 7 additions & 3 deletions packages/kbn-config-schema/src/byte_size_value/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,13 @@ export class ByteSizeValue {
public static parse(text: string): ByteSizeValue {
const match = /([1-9][0-9]*)(b|kb|mb|gb)/.exec(text);
if (!match) {
throw new Error(
`could not parse byte size value [${text}]. Value must be a safe positive integer.`
);
const number = Number(text);
if (typeof number !== 'number' || isNaN(number)) {
throw new Error(
`could not parse byte size value [${text}]. Value must be a safe positive integer.`
);
}
return new ByteSizeValue(number);
}

const value = parseInt(match[1], 0);
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions packages/kbn-config-schema/src/types/byte_size_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ describe('#defaultValue', () => {
).toMatchSnapshot();
});

test('can be a string-formatted number', () => {
expect(
byteSize({
defaultValue: '1024',
}).validate(undefined)
).toMatchSnapshot();
});

test('can be a number', () => {
expect(
byteSize({
Expand Down

0 comments on commit 0e8cea9

Please sign in to comment.