Skip to content

Support fields ids as keys in plain objects #1170

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

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

o-samwal
Copy link

This PR is an adaptation of the Closure Library's KeyOption provided by goog.proto2.ObjectSerializer

It allows to read, produce and verify a plain object using its fields ids as keys.
Unlike Closure Library, by default the names of the fields are used. To use the ids, it is necessary to specify it with an optional boolean parameter.

We use the ids of the fields in our payloads to reduce their size and pseudo-obfuscate the data.
We would like to accomplish the same with dcodeio/protobuf.js.

With the message

message MyMessage {
  string foo = 1;
  uint32 bar = 2;
}

We can create this plain object

{"foo": "value", "bar": 15}

Or this one by using root.lookupType("MyMessage").toObject(obj, {useId: true}) :

{"1": "value", "2": 15}

We can still convert {"foo": "value", "bar": 15} into a valid MyMessage message using
root.lookupType("MyMessage").fromObject(obj)

We can also convert {"1": "value", "2": 15} into a valid MyMessage message using
root.lookupType("MyMessage").fromObject(obj, true).
The fields names are resolved during the conversion.

Finally, we can verify a plain object with ids as keys by using
root.lookupType("MyMessage").verify({"1": "value", "2": 15}, true).

Like before, the message instances continue to use the fields names.
There is no breaking change : if no extra parameter is specified, the conversions continue to use the fields names.

@alexander-fenster
Copy link
Contributor

@o-samwal Hi there! 👋

Can you share the specific use case why you might need to use field IDs as keys in JSON representation of the protobuf objects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants