Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make toPlainMessage idempotent #588

Merged
merged 1 commit into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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