Coverage for src/taipanstack/utils/serialization.py: 100%
14 statements
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
1"""
2Serialization utilities.
4Provides an optimized default encoder for use with ``orjson.dumps``.
5"""
7from taipanstack.core.result import Err, Ok
9__all__ = ["default_encoder"]
12def _encode_ok(obj: Ok[object]) -> dict[str, object]:
13 """Encode an Ok result."""
14 if isinstance(obj.ok_value, dict):
15 return {"status": "success", **obj.ok_value}
16 return {"status": "success", "data": obj.ok_value}
19def _encode_err(obj: Err[object]) -> dict[str, object]:
20 """Encode an Err result."""
21 return {"status": "error", "message": str(obj.err_value)}
24def default_encoder(obj: object) -> dict[str, object]:
25 """Default encoder for orjson.dumps handling Result types.
27 Intercepts objects of type ``Ok`` and ``Err``:
28 - ``Ok(value)``: Returns ``{"status": "success"}`` merged with ``value`` if
29 ``value`` is a dict. Otherwise returns ``{"status": "success", "data": value}``.
30 - ``Err(error)``: Returns ``{"status": "error", "message": str(error)}``.
32 Args:
33 obj: The object to encode.
35 Returns:
36 A serializable representation of the object.
38 Raises:
39 TypeError: If the object type is not supported.
41 Example:
42 >>> import orjson
43 >>> orjson.dumps(Ok({"id": 1}), default=default_encoder)
44 b'{"status":"success","id":1}'
45 >>> orjson.dumps(Err(ValueError("oops")), default=default_encoder)
46 b'{"status":"error","message":"oops"}'
48 """
49 if isinstance(obj, Ok):
50 return _encode_ok(obj)
51 if isinstance(obj, Err):
52 return _encode_err(obj)
53 raise TypeError(f"Type {type(obj).__name__} is not JSON serializable")