Skip to content

Commit

Permalink
fix(specs): built-in ops accept also int (generated)
Browse files Browse the repository at this point in the history
algolia/api-clients-automation#3450

Co-authored-by: algolia-bot <[email protected]>
Co-authored-by: Kai Welke <[email protected]>
Co-authored-by: Pierre Millot <[email protected]>
  • Loading branch information
3 people committed Jul 31, 2024
1 parent 7a43b0e commit 238aad7
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 5 deletions.
18 changes: 13 additions & 5 deletions algoliasearch/search/models/built_in_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
from json import loads
from typing import Any, Dict, Self

from pydantic import BaseModel, ConfigDict, Field, StrictStr
from pydantic import BaseModel, ConfigDict, Field

from algoliasearch.search.models.built_in_operation_type import BuiltInOperationType
from algoliasearch.search.models.built_in_operation_value import BuiltInOperationValue


class BuiltInOperation(BaseModel):
Expand All @@ -20,9 +21,7 @@ class BuiltInOperation(BaseModel):
"""

operation: BuiltInOperationType = Field(alias="_operation")
value: StrictStr = Field(
description="Value that corresponds to the operation, for example an `Increment` or `Decrement` step, or an `Add` or `Remove` value."
)
value: BuiltInOperationValue

model_config = ConfigDict(
use_enum_values=True, populate_by_name=True, validate_assignment=True
Expand Down Expand Up @@ -51,6 +50,8 @@ def to_dict(self) -> Dict[str, Any]:
exclude={},
exclude_none=True,
)
if self.value:
_dict["value"] = self.value.to_dict()
return _dict

@classmethod
Expand All @@ -63,6 +64,13 @@ def from_dict(cls, obj: Dict) -> Self:
return cls.model_validate(obj)

_obj = cls.model_validate(
{"_operation": obj.get("_operation"), "value": obj.get("value")}
{
"_operation": obj.get("_operation"),
"value": (
BuiltInOperationValue.from_dict(obj.get("value"))
if obj.get("value") is not None
else None
),
}
)
return _obj
108 changes: 108 additions & 0 deletions algoliasearch/search/models/built_in_operation_value.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# coding: utf-8

"""
Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
"""

from __future__ import annotations

from json import dumps, loads
from typing import Dict, Optional, Self, Union

from pydantic import (
BaseModel,
Field,
StrictInt,
StrictStr,
ValidationError,
model_serializer,
)


class BuiltInOperationValue(BaseModel):
"""
BuiltInOperationValue
"""

oneof_schema_1_validator: Optional[StrictStr] = Field(
default=None,
description="A string to append or remove for the `Add`, `Remove`, and `AddUnique` operations.",
)
oneof_schema_2_validator: Optional[StrictInt] = Field(
default=None,
description="A number to add, remove, or append, depending on the operation.",
)
actual_instance: Optional[Union[int, str]] = None

def __init__(self, *args, **kwargs) -> None:
if args:
if len(args) > 1:
raise ValueError(
"If a position argument is used, only 1 is allowed to set `actual_instance`"
)
if kwargs:
raise ValueError(
"If a position argument is used, keyword arguments cannot be used."
)
super().__init__(actual_instance=args[0])
else:
super().__init__(**kwargs)

@model_serializer
def unwrap_actual_instance(self) -> Optional[Union[int, str]]:
"""
Unwraps the `actual_instance` when calling the `to_json` method.
"""
return self.actual_instance

@classmethod
def from_dict(cls, obj: dict) -> Self:
return cls.from_json(dumps(obj))

@classmethod
def from_json(cls, json_str: str) -> Self:
"""Returns the object represented by the json string"""
instance = cls.model_construct()
error_messages = []

try:
instance.oneof_schema_1_validator = loads(json_str)
instance.actual_instance = instance.oneof_schema_1_validator

return instance
except (ValidationError, ValueError) as e:
error_messages.append(str(e))
try:
instance.oneof_schema_2_validator = loads(json_str)
instance.actual_instance = instance.oneof_schema_2_validator

return instance
except (ValidationError, ValueError) as e:
error_messages.append(str(e))

raise ValueError(
"No match found when deserializing the JSON string into BuiltInOperationValue with oneOf schemas: int, str. Details: "
+ ", ".join(error_messages)
)

def to_json(self) -> str:
"""Returns the JSON representation of the actual instance"""
if self.actual_instance is None:
return "null"

to_json = getattr(self.actual_instance, "to_json", None)
if callable(to_json):
return self.actual_instance.to_json()
else:
return dumps(self.actual_instance)

def to_dict(self) -> Dict:
"""Returns the dict representation of the actual instance"""
if self.actual_instance is None:
return None

to_dict = getattr(self.actual_instance, "to_dict", None)
if callable(to_dict):
return self.actual_instance.to_dict()
else:
return self.actual_instance

0 comments on commit 238aad7

Please sign in to comment.