[Part 4] Repository creation

Now that we have created the database, schema and the entities let's go ahead and create the repositories which will use the entities to interact with our database.

Create a folder called repository under src and it will have the following files:

todos.rs

use crate::entity::{prelude::*, todos};
use sea_orm::{DatabaseConnection, EntityTrait};

#[derive(Debug, Clone)]
pub struct TodosRepository {
    pub db_conn: DatabaseConnection,
}

impl TodosRepository {
    pub async fn get_todos(&self) -> Vec<todos::Model> {
        Todos::find()
            .all(&self.db_conn)
            .await
            .expect("Error while fetching all todos")
    }
}

I have imported our entity prelude, todos and SeaORM related dependencies. The struct TodosRepository has a field called db_conn which will be passed by our main later and we have implemented a get_todos method on the TodosRepository which when called will return all the todos available in our todos table.

The EntityTrait import is important because that is the trait that helps the rust compiler understand that our Todos Entity exported in prelude has find, find_by_id, etc methods. Without that import, rust will complain.

I have not focused too much on error handling part as it by itself is a huge topic and I hope to deal with it in a different series in the future but as of now we will handle it with a expect block which will panic in case of any issue happens. Ideally a good pattern would be to handle it here and return a result with appropriate information, so that the API can respond to the client with a correct status code.

prelude.rs

Here let's simply export the TodosRepository struct for others to consume.

pub use super::todos::TodosRepository;

mod.rs

Let's register our prelude and todos module here.

pub mod prelude;
mod todos;

Finally don't forget to register the repository module in main. Add the below line at the top of your main.rs

mod repository;

Conclusion

We have established our repository layer and in the next part we will try to setup the HTTP layer using actix 🤩

Did you find this article valuable?

Support Omprakash Sridharan by becoming a sponsor. Any amount is appreciated!