Skip to content

Commit

Permalink
Make toPlainMessage idempotent
Browse files Browse the repository at this point in the history
Signed-off-by: Andrew Haines <andrew@haines.org.nz>
  • Loading branch information
haines committed Oct 13, 2023
1 parent fcf1a1e commit 0d0fa90
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
8 changes: 8 additions & 0 deletions packages/protobuf-test/src/to-plain-message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,14 @@ describe("toPlainMessage", () => {
const act = toPlainMessage(new WrappersMessage(exp));
expect(act).toEqual(exp);
});
describe("on plain messages", () => {
const exp: PlainMessage<MessageFieldMessage> = {
messageField: undefined,
repeatedMessageField: [],
};
const act = toPlainMessage(exp);
expect(act).toBe(exp);
});
});

function expectPlainObject(value: unknown) {
Expand Down
11 changes: 9 additions & 2 deletions packages/protobuf/src/to-plain-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,21 @@ import { Message } from "./message.js";
import type { AnyMessage, PlainMessage } from "./message.js";

/**
* toPlainMessage returns a new object by striping
* toPlainMessage returns a new object by stripping
* all methods from a message, leaving only fields and
* oneof groups. It is recursive, meaning it applies this
* same logic to all nested message fields as well.
*
* If the argument is already a plain message, it is
* returned as-is.
*/
export function toPlainMessage<T extends Message<T>>(
message: T,
message: T | PlainMessage<T>,
): PlainMessage<T> {
if (!(message instanceof Message)) {
return message;
}

const type = message.getType();
const target = {} as AnyMessage;
for (const member of type.fields.byMember()) {
Expand Down

0 comments on commit 0d0fa90

Please sign in to comment.