Allow null input on Text values (#2682)

* Allow `null` input on `Text` values

* Update test

* Add to decode section

* Revert result
This commit is contained in:
Jaco Greeff
2020-10-05 12:54:04 +02:00
committed by GitHub
parent e3a57e14bc
commit acb565d46e
3 changed files with 11 additions and 4 deletions
+6
View File
@@ -1,5 +1,11 @@
# CHANGELOG
## 2.1.2-x
Changes:
- Allow `null` input on `Text` values
## 2.1.1 Oct 5, 2020
Upgrade priority: Low.
+2 -1
View File
@@ -10,7 +10,7 @@ describe('Text', (): void => {
const registry = new TypeRegistry();
describe('decode', (): void => {
const testDecode = (type: string, input: string | Uint8Array | { toString: () => string }, expected: string, toFn: 'toString' | 'toHex' = 'toString'): void =>
const testDecode = (type: string, input: null | string | Uint8Array | { toString: () => string }, expected: string, toFn: 'toString' | 'toHex' = 'toString'): void =>
it(`can decode from ${type}`, (): void => {
expect(new Text(registry, input)[toFn]()).toBe(expected);
});
@@ -21,6 +21,7 @@ describe('Text', (): void => {
testDecode('Raw', new Raw(registry, Uint8Array.from([102, 111, 111])), 'foo'); // no length
testDecode('object with `toString()`', { toString (): string { return 'foo'; } }, 'foo');
testDecode('hex input value', new Text(registry, '0x12345678'), '0x12345678', 'toHex');
testDecode('null', null, '');
});
describe('encode', (): void => {
+3 -3
View File
@@ -12,7 +12,7 @@ import Raw from '../codec/Raw';
const MAX_LENGTH = 128 * 1024;
/** @internal */
function decodeText (value: Text | string | AnyU8a | { toString: () => string }): string {
function decodeText (value?: null | Text | string | AnyU8a | { toString: () => string }): string {
if (isHex(value)) {
return u8aToString(hexToU8a(value.toString()));
} else if (value instanceof Uint8Array) {
@@ -35,7 +35,7 @@ function decodeText (value: Text | string | AnyU8a | { toString: () => string })
return u8aToString(value.subarray(offset, total));
}
return value.toString();
return value ? value.toString() : '';
}
/**
@@ -53,7 +53,7 @@ export default class Text extends String implements Codec {
#override: string | null = null;
constructor (registry: Registry, value: Text | string | AnyU8a | { toString: () => string } = '') {
constructor (registry: Registry, value?: null | Text | string | AnyU8a | { toString: () => string }) {
super(decodeText(value));
this.registry = registry;