diff --git a/src/cats/db/mod.rs b/src/cats/db/mod.rs index 075c636..6265b80 100644 --- a/src/cats/db/mod.rs +++ b/src/cats/db/mod.rs @@ -28,7 +28,7 @@ pub struct Db { } impl Db { - pub async fn new(pool: Pool) -> Db { + pub fn new(pool: Pool) -> Db { return Db { pool: pool }; } // Создание сервиса @@ -94,6 +94,23 @@ impl Db { }) .and_then(Iterator::collect); } + // Получение cлучайной кошки + pub fn get_random_cat(&self) -> CatResult { + let conn = match self.pool.get() { + Ok(conn) => conn, + Err(err) => panic!("{}", err), + }; + return conn.query_row("SELECT c.id, c.name, cc.name from cats c INNER JOIN cat_colors cc ON cc.id = c.color_id ORDER BY random() LIMIT 1;", + [], + |row| { + Ok(Cat { + id: row.get(0)?, + name: row.get(1)?, + color: row.get(2)?, + }) + }, + ); + } // Получение цветов pub fn get_colors(&self) -> ColorsResult { diff --git a/src/cats/mod.rs b/src/cats/mod.rs index f652aca..9db3edc 100644 --- a/src/cats/mod.rs +++ b/src/cats/mod.rs @@ -1,6 +1,6 @@ pub mod db; -use db::{Db}; use actix_web::{get, post, web, HttpResponse, Responder, Result}; +use db::Db; use serde::{Deserialize, Serialize}; #[derive(Serialize)] @@ -13,9 +13,8 @@ pub struct AddColorRequest { pub name: String, } -#[get("/cats")] +#[get("/api/cats")] pub async fn get_cats(db: web::Data) -> Result { - let cats = db.get_cats(); let res = match cats { Ok(v) => ArrayResponse { result: v }, @@ -24,6 +23,16 @@ pub async fn get_cats(db: web::Data) -> Result { return Ok(HttpResponse::Ok().json(res)); } +#[get("/api/cat/random")] +pub async fn get_random_cat(db: web::Data) -> Result { + let cats = db.get_random_cat(); + let res = match cats { + Ok(v) => v, + Err(_err) => panic!("{:?}", _err), + }; + return Ok(HttpResponse::Ok().json(res)); +} + #[get("/colors")] pub async fn get_colors(db: web::Data) -> Result { let colors = db.get_colors(); @@ -41,10 +50,7 @@ pub struct AddCatRequest { } #[post("/add/cat")] -pub async fn add_cat( - db: web::Data, - cat: web::Json, -) -> Result { +pub async fn add_cat(db: web::Data, cat: web::Json) -> Result { let _cat = cat.into_inner(); let cat = db.add_cat(_cat.name, _cat.color); let res = match cat { diff --git a/src/main.rs b/src/main.rs index 6c00969..9d4f56d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,7 +22,7 @@ pub async fn main() -> std::io::Result<()> { let manager = SqliteConnectionManager::file("cats.db"); let pool = Pool::new(manager).unwrap(); - let db = Db::new(pool.clone()).await; + let db = Db::new(pool.clone()); db.init().await; HttpServer::new(move || { @@ -33,6 +33,7 @@ pub async fn main() -> std::io::Result<()> { .service(cats::get_colors) .service(cats::add_cat) .service(cats::add_color) + .service(cats::get_random_cat) .service(Files::new("/", "./static/").index_file("index.html")) }) .bind((app.host, app.port))?