connectrpc / connect-es

The TypeScript implementation of Connect: Protobuf RPC that works.

Home Page:https://connectrpc.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Connect serialization should gracefully handle null values

khalil-omer opened this issue · comments

Describe the bug

In JavaScript, it is common to use null. In our instance, an upstream library uses null to represent an empty string field instead of the Go standard of "". This isn't inherently incompatible with Protobuf, as long as the Connect library converts null and undefined to "" before attempting serialization, which it does not. Right now, Connect throws.

And again, there is nothing inherently unreasonable about Connect's current behavior unless you consider that this is the JS ecosystem where empty strings are actually rarely used for empty strings...

To Reproduce

  1. Define a protobuf message that has a string field
  2. Pass a payload to Connect that has null instead of an empty string
  3. Connect throws rather than converting the null value to the Protobuf default value of ""

For example, consider the field direction below which may be null. (This comes from the Lexical text editor library)

{
    "children": [
        {
            "children": [
                {
                    "detail": 0,
                    "format": 0,
                    "mode": "normal",
                    "style": "",
                    "text": "1234",
                    "type": "text",
                    "version": 1
                }
            ],
            "direction": null,
            "format": "",
            "indent": 0,
            "type": "paragraph",
            "version": 1
        }
    ],
    "direction": "ltr",
    "format": "",
    "indent": 0,
    "type": "root",
    "version": 1
}

I am guessing you are passing the json you get from the text editor library directly to connect client, right? Something like this:

await client.recordEdits(textEditorOutput);

In this case it will error, one way to solve this is to use fromJson method defined on the protobuf message:

await client.recordEdits(RecordEditsRequest.fromJson(textEditorOutput));

Let me know if I misunderstood the issue.

Thanks @srikrsna-buf that fixed it. Feel free to close this if you feel that the error is intended behavior when fromJson is not used.