3
\$\begingroup\$

I am trying to make a router in Rust using Rocket.rs. I'd like to devise a way to use a default router for my more simple db tables that don't require different logic, to prevent rewriting the same functions over and over and only replacing just the type of output and input it takes.

struct Router<T> {
    router_type: T,
}

trait DefaultRouter<T> {
    #[get("/")]
    pub fn get_list(&self, connection: DbConn) -> Result<Json<Vec<T>>, Failure>;

    #[get("/<id>")]
    pub fn get(&self, id: String, connection: DbConn) -> Result<Json<T>, Failure>;

    #[post("/", format = "application/json", data = "<data>")]
    pub fn insert(&self, data: T, connection: DbConn) -> Result<status::Created<Json<T>>, Failure>;

    #[put("/<id>", format = "application/json", data = "<data>")]
    pub fn update(&self, id: String, data: Json<T>, connection: DbConn) ->
        Result<status::Created<Json<T>>, Failure>;

    #[delete("/<id>")]
    pub fn delete(&self, id: String, connection: DbConn) -> Result<status::NoContent, Failure>;

    fn created(&self, data: T) -> status::Created<Json<T>>;
    fn error_status(error: Error) -> Failure;
    fn host() -> String;
    fn port() -> String;
}

impl <T> DefaultRouter<T> for Router<T> {
    #[get("/")]
    pub fn get_list(&self, connection: DbConn) -> Result<Json<Vec<T>>, Failure> {
        //...
    }
}

What this code attempts to do is to apply the functionality defined in the trait to a given router_type. I want to be able to return data of a specific schema type without needing to define this functionality for each individual schema I have defined. Does this approach align with the intentions of rust? Or is there something better? I am still definitely a beginner, so any constructive criticism is welcome.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.