Skip to content

Commit

Permalink
Add try_get() and try_get_by_external_id() to entity_store
Browse files Browse the repository at this point in the history
As commented in #2303#discussion_r1356364285, we have many patterns
using get() or get_by_external_id() and map them None to Err.

The new APIs returns Error::UnknownEntity instead of None.

Signed-off-by: Rina Fujino <[email protected]>
  • Loading branch information
rina23q committed Oct 12, 2023
1 parent 1dffbb6 commit 3dd6d04
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion crates/core/tedge_api/src/entity_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,27 @@ impl EntityStore {
self.entities.get(entity_topic_id)
}

/// Returns information for an entity under a given device/service id .
/// Tries to get information about an entity under a given MQTT entity topic identifier.
pub fn try_get(&self, entity_topic_id: &EntityTopicId) -> Result<&EntityMetadata, Error> {
self.get(entity_topic_id)
.ok_or_else(|| Error::UnknownEntity(entity_topic_id.to_string()))
}

/// Returns information for an entity under a given device/service id.
pub fn get_by_external_id(&self, external_id: &EntityExternalId) -> Option<&EntityMetadata> {
let topic_id = self.entity_id_index.get(external_id)?;
self.get(topic_id)
}

/// Tries to get information for an entity under a given device/service id.
pub fn try_get_by_external_id(
&self,
external_id: &EntityExternalId,
) -> Result<&EntityMetadata, Error> {
self.get_by_external_id(external_id)
.ok_or_else(|| Error::UnknownEntity(external_id.into()))
}

/// Returns the MQTT identifier of the main device.
///
/// The main device is an entity with `@type: "device"`.
Expand Down

0 comments on commit 3dd6d04

Please sign in to comment.