I am using actix-web,
In the main the connection of the DB is defined and the reference is passed
let mut server = HttpServer::new(move || {
App::new()
.data(db_pool.clone()) // pass database pool to application so we can access it inside handlers
.route("/", web::get().to(index))
.configure(todo::init) // init todo routes
});
In another controller the connection is passed by reference db_pool: web::Data<PgPool>
async fn find_all(db_pool: web::Data<PgPool>) -> impl Responder {
let result = Todo::find_all(db_pool.get_ref()).await;
match result {
Ok(todos) => HttpResponse::Ok().json(todos),
_ => HttpResponse::BadRequest().body("Error trying to read all todos from database")
}
}
If I invoke the connection directly in the method, would it be optimal? , or would I be invoking the DB many times and it would not be optimal?
Example
async fn find_all() -> impl Responder {
let db_pool = sqlx_test::new::<PgPool>().await?;
let result = Todo::find_all(db_pool.get_ref()).await;
match result {
Ok(todos) => HttpResponse::Ok().json(todos),
_ => HttpResponse::BadRequest().body("Error trying to read all todos from database")
}
}