tatethurston/TwirpScript

Hope to support proto 2 default value

Closed this issue · 2 comments

in proto 2.

message SomeQuery {
  optional unit32 offset = 1;
  optional uint32 limit = 2 [default = 10];
}

I hope the generated code *.pb.ts have default value , seems look like:

    // ...
    initialize: function (): SomeQuery {
      return {
        offset: 0,
        limit: 10, // hope to be 10, not 0
      };
    },

That means, the web client code SomeQuery.initialize().limit is 10, not 0.

Hey @seasonxuan thanks for opening this.

I'm not planning to support proto2 directly in this library. I'd like any community that grows around TwirpScript to not be concerned with alternate patterns to support proto2, and I don't want to maintain branching inside TwirpScript to accommodate proto2. I'm not aware of any compelling reasons to use proto2 over proto3 for new applications, and TwirpScript's creation came quite some time after the release of proto3. Some proto2 usages will work, but won't be supported directly.

Is there a particular reason setting a "fallback" value in your application code is undesirable?

You can do something like: someQueryMessage.limit ?? 10 or someQueryMessage.limit ?? QUERY_DEFAULT_LIMIT in your application code if you need to distinguish between 0 and the value being unset. Though for this use case I suspect 0 is always an invalid limit so you could use a logical or operator ||.

That means, the web client code SomeQuery.initialize().limit is 10, not 0.

This value is actually going to be undefined not 0 for proto3 clients because the field is optional. TwirpScript does not generate a default value for optional fields in the generated initialize. If you look at the generated code, you'll see something like this (note limit is missing):

  /**
   * Initializes SomeQuery with all fields set to their default value.
   */
  initialize: function (): SomeQuery {
    return {
      offset: 0
    };
  },

@tatethurston OK, Thank you.