#connection-pool #rocket #rocket-framework #butane

butane_rocket_pool

Butane database adapter for Rocket framework

4 releases

0.5.3 Mar 31, 2024
0.5.2 May 6, 2023
0.5.1 May 6, 2023
0.5.0 Aug 2, 2021

#1520 in Database interfaces

MIT license

8KB
74 lines

butane_rocket_pool

Butane database adapter for Rocket framework

Usage

  1. Configure your database in Rocket.toml. Parameters url and backend_name are required.
[default.databases.test]
backend_name = "sqlite" #Butane's backend name
url = "test.db"
  1. Add and init database in your application's code
#[database("test")]
struct DbConn(butane_rocket_pool::Connection); 

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![create])
    .attach(DbConn::fairing())
}
  1. To use the connection with Butane functions apply two dereference operators.
#[post("/", data = "<post>")]
async fn create(db: DbConn, post: Json<Post>) -> (Status, Value) {
    let result = db.run(move |db| -> Result<Post, butane::Error> {
        let mut result = post.0;
        result.save(&**db)?;
        Post::get(&**db, result.id)
    }).await;

    match result {
        Ok(res) => (Status::Created, json!({
            "message" : "Post is created!",
            "data" : res
        })),
        Err(err) => (Status::InternalServerError, json!({
            "message" : "Can't create post!",
            "error" : format!("{}", err)
        }))
    }
}

Dependencies

~18–50MB
~854K SLoC