Normalize unset fields to null

This commit is contained in:
Simon Warta 2020-08-10 06:18:58 +02:00 committed by willclarktech
parent 7e4705b703
commit d0ff5fabca
No known key found for this signature in database
GPG Key ID: 551A86E2E398ADF7
2 changed files with 31 additions and 8 deletions

View File

@ -46,6 +46,12 @@ describe("adr27", () => {
expect(omitDefault(Review.values["ACCEPTED"])).toEqual(Review.values["ACCEPTED"]);
expect(omitDefault(Review.values["UNSPECIFIED"])).toEqual(null);
});
it("works for unset", () => {
// null and undefined both represent unset in protobuf.js serialization
expect(omitDefault(undefined)).toEqual(null);
expect(omitDefault(null)).toEqual(null);
});
});
describe("omitDefaults", () => {
@ -85,6 +91,12 @@ describe("adr27", () => {
expect(omitDefaults(Review.values["UNSPECIFIED"])).toEqual(null);
});
it("works for unset", () => {
// null and undefined both represent unset in protobuf.js serialization
expect(omitDefaults(undefined)).toEqual(null);
expect(omitDefaults(null)).toEqual(null);
});
it("works for objects", () => {
// empty
expect(omitDefaults({})).toEqual({});

View File

@ -1,4 +1,4 @@
import { isUint8Array } from "@cosmjs/utils";
import { isNonNullObject, isUint8Array } from "@cosmjs/utils";
/**
* Converts default values to null in order to tell protobuf.js
@ -7,6 +7,8 @@ import { isUint8Array } from "@cosmjs/utils";
* @see https://github.com/cosmos/cosmos-sdk/pull/6979
*/
export function omitDefault<T>(input: T): T | null {
if (input === undefined || input === null) return null;
if (typeof input === "number" || typeof input === "boolean" || typeof input === "string") {
return input || null;
}
@ -23,6 +25,10 @@ export function omitDefault<T>(input: T): T | null {
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function omitDefaults(input: any): any {
// Unset
if (input === undefined || input === null) return null;
// Protobuf element
if (
typeof input === "number" ||
typeof input === "boolean" ||
@ -33,11 +39,16 @@ export function omitDefaults(input: any): any {
return omitDefault(input);
}
return Object.keys(input).reduce(
(accumulator, key) => ({
...accumulator,
[key]: omitDefaults(input[key]),
}),
{},
);
// Object
if (isNonNullObject(input)) {
return Object.keys(input).reduce(
(accumulator, key) => ({
...accumulator,
[key]: omitDefaults((input as any)[key]),
}),
{},
);
}
throw new Error(`Input type not supported: ${typeof input}`);
}