Coverage for src / taipanstack / utils / serialization.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-05-12 21:18 +0000

1""" 

2Serialization utilities. 

3 

4Provides an optimized default encoder for use with ``orjson.dumps``. 

5""" 

6 

7from taipanstack.core.result import Err, Ok 

8 

9__all__ = ["default_encoder"] 

10 

11 

12def default_encoder(obj: object) -> dict[str, object]: 

13 """Default encoder for orjson.dumps handling Result types. 

14 

15 Intercepts objects of type ``Ok`` and ``Err``: 

16 - ``Ok(value)``: Returns ``{"status": "success"}`` merged with ``value`` if 

17 ``value`` is a dict. Otherwise returns ``{"status": "success", "data": value}``. 

18 - ``Err(error)``: Returns ``{"status": "error", "message": str(error)}``. 

19 

20 Args: 

21 obj: The object to encode. 

22 

23 Returns: 

24 A serializable representation of the object. 

25 

26 Raises: 

27 TypeError: If the object type is not supported. 

28 

29 Example: 

30 >>> import orjson 

31 >>> orjson.dumps(Ok({"id": 1}), default=default_encoder) 

32 b'{"status":"success","id":1}' 

33 >>> orjson.dumps(Err(ValueError("oops")), default=default_encoder) 

34 b'{"status":"error","message":"oops"}' 

35 

36 """ 

37 if isinstance(obj, Ok): 

38 if isinstance(obj.ok_value, dict): 

39 return {"status": "success", **obj.ok_value} 

40 return {"status": "success", "data": obj.ok_value} 

41 if isinstance(obj, Err): 

42 return {"status": "error", "message": str(obj.err_value)} 

43 raise TypeError(f"Type {type(obj).__name__} is not JSON serializable")