Deduplicate some entity registry code (#85541)

pull/85380/head
Erik Montnemery 2023-01-16 22:06:52 +01:00 committed by GitHub
parent 612f93d636
commit 788edc21fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 44 deletions

View File

@ -46,9 +46,9 @@ def websocket_list_entities(
msg_json = (
msg_json_prefix
+ ",".join(
entry.json_repr
entry.partial_json_repr
for entry in registry.entities.values()
if entry.json_repr is not None
if entry.partial_json_repr is not None
)
+ "]}"
)
@ -259,32 +259,10 @@ def websocket_remove_entity(
connection.send_message(websocket_api.result_message(msg["id"]))
@callback
def _entry_dict(entry: er.RegistryEntry) -> dict[str, Any]:
"""Convert entry to API format."""
return {
"area_id": entry.area_id,
"config_entry_id": entry.config_entry_id,
"device_id": entry.device_id,
"disabled_by": entry.disabled_by,
"entity_category": entry.entity_category,
"entity_id": entry.entity_id,
"has_entity_name": entry.has_entity_name,
"hidden_by": entry.hidden_by,
"icon": entry.icon,
"id": entry.id,
"name": entry.name,
"original_name": entry.original_name,
"platform": entry.platform,
"translation_key": entry.translation_key,
"unique_id": entry.unique_id,
}
@callback
def _entry_ext_dict(entry: er.RegistryEntry) -> dict[str, Any]:
"""Convert entry to API format."""
data = _entry_dict(entry)
data = entry.as_partial_dict
data["aliases"] = entry.aliases
data["capabilities"] = entry.capabilities
data["device_class"] = entry.device_class

View File

@ -153,13 +153,9 @@ class RegistryEntry:
return self.hidden_by is not None
@property
def json_repr(self) -> str | None:
"""Return a cached JSON representation of the entry."""
if self._json_repr is not None:
return self._json_repr
try:
dict_repr = {
def as_partial_dict(self) -> dict[str, Any]:
"""Return a partial dict representation of the entry."""
return {
"area_id": self.area_id,
"config_entry_id": self.config_entry_id,
"device_id": self.device_id,
@ -176,6 +172,15 @@ class RegistryEntry:
"translation_key": self.translation_key,
"unique_id": self.unique_id,
}
@property
def partial_json_repr(self) -> str | None:
"""Return a cached partial JSON representation of the entry."""
if self._json_repr is not None:
return self._json_repr
try:
dict_repr = self.as_partial_dict
object.__setattr__(self, "_json_repr", JSON_DUMP(dict_repr))
except (ValueError, TypeError):
_LOGGER.error(