|
| 1 | +import typing |
| 2 | + |
| 3 | +import betterproto2 |
| 4 | + |
| 5 | +from betterproto2_compiler.lib.google.protobuf import ( |
| 6 | + ListValue as VanillaListValue, |
| 7 | + NullValue, |
| 8 | + Struct as VanillaStruct, |
| 9 | + Value as VanillaValue, |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +class Struct(VanillaStruct): |
| 14 | + # TODO typing |
| 15 | + def to_dict( |
| 16 | + self, |
| 17 | + *, |
| 18 | + output_format: betterproto2.OutputFormat = betterproto2.OutputFormat.PROTO_JSON, |
| 19 | + casing: betterproto2.Casing = betterproto2.Casing.CAMEL, |
| 20 | + include_default_values: bool = False, |
| 21 | + ) -> dict[str, typing.Any] | typing.Any: |
| 22 | + # If the output format is PYTHON, we should have kept the wraped type without building the real class |
| 23 | + assert output_format == betterproto2.OutputFormat.PROTO_JSON |
| 24 | + |
| 25 | + json = {} |
| 26 | + for name, value in self.fields.items(): |
| 27 | + json[name] = value.to_dict(casing=casing) |
| 28 | + return json |
| 29 | + |
| 30 | + |
| 31 | +class Value(VanillaValue): |
| 32 | + def to_dict( |
| 33 | + self, |
| 34 | + *, |
| 35 | + output_format: betterproto2.OutputFormat = betterproto2.OutputFormat.PROTO_JSON, |
| 36 | + casing: betterproto2.Casing = betterproto2.Casing.CAMEL, |
| 37 | + include_default_values: bool = False, |
| 38 | + ) -> dict[str, typing.Any] | typing.Any: |
| 39 | + # If the output format is PYTHON, we should have kept the wraped type without building the real class |
| 40 | + assert output_format == betterproto2.OutputFormat.PROTO_JSON |
| 41 | + |
| 42 | + match self: |
| 43 | + case Value(null_value=NullValue()): |
| 44 | + return None |
| 45 | + case Value(number_value=float(number_value)): |
| 46 | + return number_value |
| 47 | + case Value(string_value=str(string_value)): |
| 48 | + return string_value |
| 49 | + case Value(bool_value=bool(bool_value)): |
| 50 | + return bool_value |
| 51 | + case Value(struct_value=struct_value) if struct_value is not None: |
| 52 | + return struct_value.to_dict(casing=casing) |
| 53 | + case Value(list_value=list_value) if list_value is not None: |
| 54 | + return list_value.to_dict(casing=casing) |
| 55 | + |
| 56 | + |
| 57 | +class ListValue(VanillaListValue): |
| 58 | + def to_dict( |
| 59 | + self, |
| 60 | + *, |
| 61 | + output_format: betterproto2.OutputFormat = betterproto2.OutputFormat.PROTO_JSON, |
| 62 | + casing: betterproto2.Casing = betterproto2.Casing.CAMEL, |
| 63 | + include_default_values: bool = False, |
| 64 | + ) -> dict[str, typing.Any] | typing.Any: |
| 65 | + # If the output format is PYTHON, we should have kept the wraped type without building the real class |
| 66 | + assert output_format == betterproto2.OutputFormat.PROTO_JSON |
| 67 | + |
| 68 | + json = [] |
| 69 | + for value in self.values: |
| 70 | + json.append(value.to_dict(casing=casing)) |
| 71 | + return json |
0 commit comments