Skip to content

Commit 132833a

Browse files
committed
rest-api: add generic registry validation
Change-Id: I2954151d52e6b6dd02df72efc4be956219d41ef2
1 parent cab83dc commit 132833a

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

cmk/gui/openapi/framework/model/converter.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
44
# conditions defined in the file COPYING, which is part of this source code package.
55
import ipaddress
6-
from collections.abc import Callable
6+
from collections.abc import Callable, Mapping
77
from dataclasses import dataclass
88
from typing import Literal
99

@@ -49,6 +49,34 @@ def _with_type_check(value: T) -> object:
4949
)
5050

5151

52+
@dataclass(slots=True)
53+
class RegistryConverter[T]:
54+
registry_or_getter: Mapping[str, T] | Callable[[], Mapping[str, T]]
55+
custom_error_message: str | None = None
56+
57+
@property
58+
def _registry(self) -> Mapping[str, T]:
59+
if not isinstance(self.registry_or_getter, Mapping):
60+
self.registry_or_getter = self.registry_or_getter()
61+
62+
return self.registry_or_getter
63+
64+
def validate(self, value: str) -> str:
65+
"""Validates that the given value is in the registry."""
66+
if value not in self._registry:
67+
raise ValueError(
68+
self.custom_error_message
69+
or f"Value {value!r} is not allowed, valid options are: {', '.join(sorted(self._registry))}"
70+
)
71+
72+
return value
73+
74+
def value(self, value: str) -> T:
75+
"""Returns the value from the registry."""
76+
self.validate(value)
77+
return self._registry[value]
78+
79+
5280
@dataclass(slots=True)
5381
class HostConverter:
5482
type PermissionType = Literal["setup_write", "setup_read", "monitor"]

0 commit comments

Comments
 (0)