bufbuild / protobuf-es

Protocol Buffers for ECMAScript. The only JavaScript Protobuf library that is fully-compliant with Protobuf conformance tests.
Apache License 2.0
1.16k stars 69 forks source link

Allowing to override default options when generating #991

Closed blaz-rupnik-veza closed 1 month ago

blaz-rupnik-veza commented 1 month ago

I am trying to override the fromJson serialization method. By default the ignoreUnknownFields is set to false, I would like to set it to true when generating so that my frontend code will be backwards compatible when new api is available. Couldn't find any simple way to do this.

timostamm commented 1 month ago

I'm not sure what you mean with "override". You can simply provide the option ignoreUnknownFields: true when calling fromJson.

If you write an RPC framework, you can let the framework handle serialization, and have it use whatever options you prefer. That's what https://github.com/connectrpc/connect-es does.

You can also curry fromJson for your project, it's just a function. For example:

import {type DescMessage, fromJson, type JsonReadOptions, type JsonValue, type MessageShape} from "@bufbuild/protobuf";

export function myFromJson<Desc extends DescMessage>(
  schema: Desc,
  json: JsonValue,
  options?: Partial<JsonReadOptions>,
): MessageShape<Desc> {
  return fromJson(schema, json, {
    ignoreUnknownFields: true,
    ...options,
  });
}

Closing, since I don't think there's anything to do for us, but let me know if I missed something.