summaryrefslogtreecommitdiff
path: root/venv/lib/python3.11/site-packages/litestar/dto/field.py
blob: 7ef8a390e22bfcd850b8ae0a6094d8bbc668530c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""DTO domain types."""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Literal

__all__ = (
    "DTO_FIELD_META_KEY",
    "DTOField",
    "Mark",
    "dto_field",
)

DTO_FIELD_META_KEY = "__dto__"


class Mark(str, Enum):
    """For marking field definitions on domain models."""

    READ_ONLY = "read-only"
    """To mark a field that can be read, but not updated by clients."""
    WRITE_ONLY = "write-only"
    """To mark a field that can be written to, but not read by clients."""
    PRIVATE = "private"
    """To mark a field that can neither be read or updated by clients."""


@dataclass
class DTOField:
    """For configuring DTO behavior on model fields."""

    mark: Mark | Literal["read-only", "write-only", "private"] | None = None
    """Mark the field as read-only, or private."""


def dto_field(mark: Literal["read-only", "write-only", "private"] | Mark) -> dict[str, DTOField]:
    """Create a field metadata mapping.

    Args:
        mark: A DTO mark for the field, e.g., "read-only".

    Returns:
        A dict for setting as field metadata, such as the dataclass "metadata" field key, or the SQLAlchemy "info"
        field.

        Marking a field automates its inclusion/exclusion from DTO field definitions, depending on the DTO's purpose.
    """
    return {DTO_FIELD_META_KEY: DTOField(mark=Mark(mark))}