This commit is contained in:
Кобелев Андрей Андреевич 2022-10-13 13:51:13 +03:00
parent 3360706756
commit c4db474fc8
3 changed files with 33 additions and 9 deletions

View File

@ -28,7 +28,7 @@ pub struct Db {
} }
impl Db { impl Db {
pub async fn new(pool: Pool) -> Db { pub fn new(pool: Pool) -> Db {
return Db { pool: pool }; return Db { pool: pool };
} }
// Создание сервиса // Создание сервиса
@ -94,6 +94,23 @@ impl Db {
}) })
.and_then(Iterator::collect); .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 { pub fn get_colors(&self) -> ColorsResult {

View File

@ -1,6 +1,6 @@
pub mod db; pub mod db;
use db::{Db};
use actix_web::{get, post, web, HttpResponse, Responder, Result}; use actix_web::{get, post, web, HttpResponse, Responder, Result};
use db::Db;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize)] #[derive(Serialize)]
@ -13,9 +13,8 @@ pub struct AddColorRequest {
pub name: String, pub name: String,
} }
#[get("/cats")] #[get("/api/cats")]
pub async fn get_cats(db: web::Data<Db>) -> Result<impl Responder> { pub async fn get_cats(db: web::Data<Db>) -> Result<impl Responder> {
let cats = db.get_cats(); let cats = db.get_cats();
let res = match cats { let res = match cats {
Ok(v) => ArrayResponse { result: v }, Ok(v) => ArrayResponse { result: v },
@ -24,6 +23,16 @@ pub async fn get_cats(db: web::Data<Db>) -> Result<impl Responder> {
return Ok(HttpResponse::Ok().json(res)); return Ok(HttpResponse::Ok().json(res));
} }
#[get("/api/cat/random")]
pub async fn get_random_cat(db: web::Data<Db>) -> Result<impl Responder> {
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")] #[get("/colors")]
pub async fn get_colors(db: web::Data<Db>) -> Result<impl Responder> { pub async fn get_colors(db: web::Data<Db>) -> Result<impl Responder> {
let colors = db.get_colors(); let colors = db.get_colors();
@ -41,10 +50,7 @@ pub struct AddCatRequest {
} }
#[post("/add/cat")] #[post("/add/cat")]
pub async fn add_cat( pub async fn add_cat(db: web::Data<Db>, cat: web::Json<AddCatRequest>) -> Result<impl Responder> {
db: web::Data<Db>,
cat: web::Json<AddCatRequest>,
) -> Result<impl Responder> {
let _cat = cat.into_inner(); let _cat = cat.into_inner();
let cat = db.add_cat(_cat.name, _cat.color); let cat = db.add_cat(_cat.name, _cat.color);
let res = match cat { let res = match cat {

View File

@ -22,7 +22,7 @@ pub async fn main() -> std::io::Result<()> {
let manager = SqliteConnectionManager::file("cats.db"); let manager = SqliteConnectionManager::file("cats.db");
let pool = Pool::new(manager).unwrap(); let pool = Pool::new(manager).unwrap();
let db = Db::new(pool.clone()).await; let db = Db::new(pool.clone());
db.init().await; db.init().await;
HttpServer::new(move || { HttpServer::new(move || {
@ -33,6 +33,7 @@ pub async fn main() -> std::io::Result<()> {
.service(cats::get_colors) .service(cats::get_colors)
.service(cats::add_cat) .service(cats::add_cat)
.service(cats::add_color) .service(cats::add_color)
.service(cats::get_random_cat)
.service(Files::new("/", "./static/").index_file("index.html")) .service(Files::new("/", "./static/").index_file("index.html"))
}) })
.bind((app.host, app.port))? .bind((app.host, app.port))?