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 {
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 {

View File

@ -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<Db>) -> Result<impl Responder> {
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<Db>) -> Result<impl Responder> {
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")]
pub async fn get_colors(db: web::Data<Db>) -> Result<impl Responder> {
let colors = db.get_colors();
@ -41,10 +50,7 @@ pub struct AddCatRequest {
}
#[post("/add/cat")]
pub async fn add_cat(
db: web::Data<Db>,
cat: web::Json<AddCatRequest>,
) -> Result<impl Responder> {
pub async fn add_cat(db: web::Data<Db>, cat: web::Json<AddCatRequest>) -> Result<impl Responder> {
let _cat = cat.into_inner();
let cat = db.add_cat(_cat.name, _cat.color);
let res = match cat {

View File

@ -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))?