scuffle_cedar_policy/
entities_builder.rs

1use crate::{CedarEntity, Entity};
2
3/// A request builder used to construct a [cedar_policy::Entities].
4pub struct EntitiesBuilder<'a> {
5    entities: Vec<cedar_policy::Entity>,
6    schema: Option<&'a cedar_policy::Schema>,
7}
8
9impl Default for EntitiesBuilder<'_> {
10    fn default() -> Self {
11        Self::new(None)
12    }
13}
14
15/// All the errors that can take place when building a request
16#[derive(thiserror::Error, Debug)]
17pub enum EntitiesBuilderError {
18    /// Error while adding an entity
19    #[error(transparent)]
20    EntitiesError(#[from] Box<cedar_policy::entities_errors::EntitiesError>),
21    /// Error while serializing to json
22    #[error(transparent)]
23    Json(#[from] serde_json::Error),
24}
25
26impl<'a> EntitiesBuilder<'a> {
27    /// Create a new request builder given a schema.
28    pub fn new(schema: Option<&'a cedar_policy::Schema>) -> Self {
29        Self {
30            schema,
31            entities: Vec::new(),
32        }
33    }
34
35    /// Add an entity to the builder.
36    /// See [Self::add_entity] for a mut ref builder method.
37    pub fn with_entity<E: CedarEntity>(mut self, entity: &Entity<E>) -> Result<Self, EntitiesBuilderError> {
38        self.add_entity(entity)?;
39        Ok(self)
40    }
41
42    /// Add an entity to the builder.
43    /// See [Self::with_entity] for a owned builder method.
44    pub fn add_entity<E: CedarEntity>(&mut self, entity: &Entity<E>) -> Result<&mut Self, EntitiesBuilderError> {
45        let entity = serde_json::to_value(entity)?;
46        self.entities
47            .push(cedar_policy::Entity::from_json_value(entity, self.schema).map_err(Box::new)?);
48        Ok(self)
49    }
50
51    /// Build a request given a principal, resource and a ctx.
52    pub fn build(self) -> Result<cedar_policy::Entities, EntitiesBuilderError> {
53        cedar_policy::Entities::empty()
54            .add_entities(self.entities, self.schema)
55            .map_err(Box::new)
56            .map_err(EntitiesBuilderError::EntitiesError)
57    }
58}