Label model
use serde::{Deserialize, Serialize};
use tokio_postgres::{types::ToSql, Row};
pub trait DatabaseModelTrait {
fn from_row(row: &Row) -> Self;
fn create_to_sql_value(&self) -> Vec<&(dyn ToSql + Sync)>;
fn get_id(&self) -> Option<i32>;
fn get_table_name(&self) -> String;
}
use serde::{Deserialize, Serialize};
use tokio_postgres::{types::ToSql, Row};
#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct Label {
pub label_id: Option<i32>, // The ID of the label
pub serial_number: Option<String>, // The serial number of the label
pub brand: Option<String>, // The brand of the label
pub models: Option<String>, // The models associated with the label
}
/// #[async_trait] bu
unsafe impl Send for Label {}
unsafe impl Sync for Label {}
impl Label {
// Constructor for creating a new Label instance
pub fn new(
label_id: Option<i32>,
serial_number: Option<String>,
brand: Option<String>,
models: Option<String>,
) -> Label {
Label {
label_id, // Initialize the label ID
serial_number, // Initialize the serial number of the label
brand, // Initialize the brand of the label
models, // Initialize the models associated with the label
}
}
}
impl DatabaseModelTrait for Label {//Code}
repository.rs
use std::fmt::Debug;
use async_trait::async_trait;
use serde::Serialize;
use tokio_postgres::Row;
#[async_trait]
pub trait DatabaseRepositoryTrait<T> {
async fn add(db: &Database, model: &T) -> Result<(), DbError>;
async fn get_by_id(db: &Database, model: &T) -> Result<Option<T>, DbError>;
async fn update(db: &Database, model: &T) -> Result<(), DbError>;
async fn delete(db: &Database, model: &T) -> Result<(), DbError>;
async fn get_all(db: &Database, model: &T) -> Result<Vec<T>, DbError>;
}
pub struct DatabaseRepository<T> {
phantom: std::marker::PhantomData<T>,
}
#[async_trait]
impl<T: DatabaseModelTrait + Debug + Serialize + Send + Sync> DatabaseRepositoryTrait<T>
for DatabaseRepository<T>
{
async fn add(db: &Database, model: &T) -> Result<(), DbError> {
let query: String = QueryCreator::generate_create_query(model).unwrap();
let lab1 = Label::new(Some(1), None, None, None);
let vecT = vec![&lab1];
let u = QueryCreator::generate_delete_all_query(vecT);
println!("{:?}", u);
db.execute_for_cud(&query, &[]).await?;
Ok(())
}
Controller
#[async_trait]
pub trait ControllerTrait<T> {
async fn add_label(
model: web::Json<&T>,
db: web::Data<Database>,
) -> Result<HttpResponse, http_error>;
}
pub struct Controller<T> {
phantom: std::marker::PhantomData<T>,
}
#[async_trait]
impl<T: DatabaseModelTrait + Debug + Serialize + Send + Sync> ControllerTrait<T> for Controller<T> {
async fn add_label(
model: web::Json<&T>,
db: web::Data<Database>,
) -> Result<HttpResponse, http_error> {
let model_data = model.into_inner();
DR::<T>::add(db.get_ref(), model_data).await;
Ok(HttpResponse::Ok().json("Label added successfully"))
}
}
Router.rs
use actix_web::{error, web, Error, HttpRequest, HttpResponse};
pub fn configure_routes(config: &mut web::ServiceConfig) {
config.service(
web::scope("/api")
.service(web::resource("/v2").route(web::post()
.to(Controller::<&Label>::add_label)))
);
}
I get trait bounds are not satisfied error.
Error:
“the function or associated item add_label
exists for struct Controller<&Label>
, but its trait bounds were not satisfied
items from traits can only be used if the trait is implemented and in scope”
the function or associated item add_label
exists for struct Controller<&Label>
, but its trait bounds were not satisfied
–> srcroutes.rs:9:39
|
9 | .to(Controller::<&Label>::add_label)))
| ^^^^^^^^^ function or associated item cannot be called on Controller<&Label>
due to unsatisfied trait bounds
|
::: srccontrollersproduct_controller.rs:23:1
|
23 | pub struct Controller<T> {
| ———————— function or associated item add_label
not found for this struct because it doesn’t satisfy Controller<&Label>: ControllerTrait<&Label>
|
note: trait bound &Label: DatabaseModelTrait
was not satisfied
–> srccontrollersproduct_controller.rs:28:9
|
28 | impl<T: DatabaseModelTrait + Debug + Serialize + Send + Sync> ControllerTrait<T> for Controller<T> {
| ^^^^^^^^^^^^^^^^^^ —————— ————-
| |
| unsatisfied trait bound introduced here
= help: items from traits can only be used if the trait is implemented and in scope
note: ControllerTrait
defines an item add_label
, perhaps you need to implement it
–> srccontrollersproduct_controller.rs:16:1
|
16 | pub trait ControllerTrait<T> {
Other error:
function or associated item add_label
not found for this struct because it doesn’t satisfy Controller<&Label>: ControllerTrait<&Label>
trait bound &Label: DatabaseModelTrait
was not satisfied.
ControllerTrait
defines an item add_label
, perhaps you need to implement it.
I try to use async trait. Since I will have the same operations in the repository and controller, I abstract as much as possible with Generics to avoid duplication of code. and all I have to do is specify a struct in Route.
However, when I call my Controller code inside or outside Route, my code always gives the same error.
user24372707 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.