Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

insert

📍 Method

insert(entity: Entity) -> Result<(), repox::InsertError<Entity>>

This method allows you to insert a new entity into the repository. It expects an instance of the entity you want to insert and returns Ok(()) on success. Your repository must implement the trait of Insert<T> for every entity type T you want to be able to insert.

🧩 Detailed Example:

Bob just came back from a big tech conference and is stoked on “sharding our widgets for webscale.” The ids are going to be generated by some external service, so we need to now be able to support inserting new widgets into our data store. It’s only a matter of time before we need to support this so let’s do it now!

use repox::Repo;

// Our new "webscale" widget
#[derive(Debug, Clone, PartialEq, repox::Entity)]
pub struct Widget {
    pub id: u128,
    pub name: std::sync::Arc<str>,
}

// We need to be able to insert these widgets into our data store
pub trait InsertableWidgetRepo: Repo + repox::Insert<Widget> {}

// Our new high-end data store that only works with widgets
#[derive(Debug, Default)]
pub struct WidgetData {
    pub data: dashmap::DashMap<u128, Widget>,
}

// look how proactive we are by implementing the Repo trait
impl Repo for WidgetData {}
impl InsertableWidgetRepo for WidgetData {}

// this is where it get's serious, stop goofing around Ben!
impl repox::Insert<Widget> for WidgetData {
    async fn exec(&self, widget: Widget)
    -> Result<(), repox::InsertError<Widget>>
    {
        self.data.insert(widget.id, widget);
        Ok(())
    }
}

// The guys back at the lab are never going to believe this, we
// just implemented an insert method for our widget repo!  Better
// Wire up a test to make sure it works and we can show it off to
// the team!
pollster::block_on(async {
let data = WidgetData::default();
let widget = Widget {
    id: 2_605_927_472,
    name: "QuantumTunnelVortex".into(),
};

// we're taking a quantum leap here by inserting this into our repo
data.insert(widget.clone()).await.unwrap();

// make sure it actually got in there, we don't want to look like fools
assert_eq!(data.data.get(&widget.id).unwrap().clone(), widget);

// Cowabunga! 🥷🐢
});

🧪 Mock Example:

use repox::{Repo, Entity};

#[derive(Debug, Clone, PartialEq, Entity)]
pub struct Widget {
    pub id: u32,
    pub name: String,
}

#[repox::mockall]
pub trait WidgetInsert: Repo + repox::Insert<Widget> {}

let mut repo = MockWidgetInsert::new();
repo.expect_insert::<Widget>()
    .withf(|widget|{
        *widget == Widget { id: 7, name: "Sproket".into() }
    })
    .returning(repox::mock::ok_val(()));

pollster::block_on(async {
repo.insert(Widget { id: 7, name: "Sproket".into() } ).await.unwrap();
});

// Pretty cool 🧊