Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON response with validation #13

Merged
merged 1 commit into from
Dec 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 20 additions & 22 deletions src/app/actions/home.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@ pub fn find_all_homes(conn: &mut PgConnection) -> Result<Vec<home::Home>, DbErro
Ok(get_homes)
}

pub fn find_home_by_uid(
conn: &mut PgConnection,
uid: Uuid,
) -> Result<Option<home::Home>, DbError> {
pub fn find_home_by_uid(conn: &mut PgConnection, uid: Uuid) -> Result<Option<home::Home>, DbError> {
use crate::schema::homes::dsl::*;

let home = homes
Expand All @@ -33,28 +30,29 @@ pub fn insert_new_home(
) -> Result<home::Home, DbError> {
use crate::schema::homes::dsl::*;

let new_home = home::Home {
id: Uuid::new_v4().to_string(),
title: form.title.to_owned(),
body: form.body.to_owned()
};
match form.validate() {
Ok(_) => {
let new_home = home::Home {
id: Uuid::new_v4().to_string(),
title: form.title.to_owned(),
body: form.body.to_owned(),
};

diesel::insert_into(homes).values(&new_home).execute(conn)?;
diesel::insert_into(homes).values(&new_home).execute(conn)?;

Ok(new_home)
Ok(new_home)
}
Err(error) => Err(DbError::from(error)),
}
}

pub fn delete_home(
conn: &mut PgConnection,
uid: Uuid,
) -> Result<String, DbError> {
use crate::schema::homes::dsl::*;
pub fn delete_home(conn: &mut PgConnection, uid: Uuid) -> Result<String, DbError> {
use crate::schema::homes::dsl::*;

let result = diesel::delete(homes.filter(id.eq(uid.to_string())))
.execute(conn);
let result = diesel::delete(homes.filter(id.eq(uid.to_string()))).execute(conn);

match result {
Ok(_) => Ok("Success".to_string()),
Err(e) => Err(DbError::from(e)),
}
match result {
Ok(_) => Ok("Success".to_string()),
Err(e) => Err(DbError::from(e)),
}
}
73 changes: 35 additions & 38 deletions src/app/api/home.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use actix_web::{web, get, post, delete, Result, Responder, error, HttpResponse};
use diesel::{PgConnection, r2d2};
use actix_web::{delete, error, get, post, web, HttpResponse, Responder, Result};
use diesel::{r2d2, PgConnection};
use uuid::Uuid;

use crate::app::actions;
Expand All @@ -10,58 +10,55 @@ type DbPool = r2d2::Pool<r2d2::ConnectionManager<PgConnection>>;
#[get("/home")]
async fn all_homes(pool: web::Data<DbPool>) -> Result<impl Responder> {
let all_homes = web::block(move || {
let mut conn = pool.get()?;
actions::home::find_all_homes(&mut conn)
let mut conn = pool.get()?;
actions::home::find_all_homes(&mut conn)
})
.await?
.map_err(error::ErrorInternalServerError)?;
.map_err(error::ErrorBadRequest)?;

Ok(HttpResponse::Ok().json(all_homes))
Ok(HttpResponse::Ok().json(all_homes))
}

#[get("/home/{home_id}")]
async fn find_home(pool: web::Data<DbPool>, home_id: web::Path<Uuid>) -> Result<impl Responder> {
let home_uid = home_id.into_inner();
let home = web::block(move || {
let mut conn = pool.get()?;
actions::home::find_home_by_uid(&mut conn, home_uid)
})
.await?
.map_err(error::ErrorInternalServerError)?;
let home_uid = home_id.into_inner();
let home = web::block(move || {
let mut conn = pool.get()?;
actions::home::find_home_by_uid(&mut conn, home_uid)
})
.await?
.map_err(error::ErrorBadRequest)?;

Ok(match home {
Some(home) => HttpResponse::Ok().json(home),
None => HttpResponse::NotFound().body(format!("No Home found with UID: {home_uid}")),
})
Ok(match home {
Some(home) => HttpResponse::Ok().json(home),
None => HttpResponse::NotFound().json(format!("No Home found with UID: {home_uid}")),
})
}

#[post("/home")]
async fn add_home(
pool: web::Data<DbPool>,
form: web::Json<models::home::NewHome>,
pool: web::Data<DbPool>,
form: web::Json<models::home::NewHome>,
) -> Result<impl Responder> {
let home = web::block(move || {
let mut conn = pool.get()?;
actions::home::insert_new_home(&mut conn, &form)
})
.await?
.map_err(error::ErrorInternalServerError)?;
let home = web::block(move || {
let mut conn = pool.get()?;
actions::home::insert_new_home(&mut conn, &form)
})
.await?
.map_err(error::ErrorBadRequest)?;

Ok(HttpResponse::Created().json(home))
Ok(HttpResponse::Created().json(home))
}

#[delete("/home/{home_id}")]
async fn delete_home(
pool: web::Data<DbPool>,
home_id: web::Path<Uuid>,
) -> Result<impl Responder> {
let home_uid = home_id.into_inner();
let home = web::block(move || {
let mut conn = pool.get()?;
actions::home::delete_home(&mut conn, home_uid)
})
.await?
.map_err(error::ErrorInternalServerError)?;
async fn delete_home(pool: web::Data<DbPool>, home_id: web::Path<Uuid>) -> Result<impl Responder> {
let home_uid = home_id.into_inner();
let home = web::block(move || {
let mut conn = pool.get()?;
actions::home::delete_home(&mut conn, home_uid)
})
.await?
.map_err(error::ErrorBadRequest)?;

Ok(HttpResponse::Created().json(home))
Ok(HttpResponse::Created().json(home))
}
17 changes: 15 additions & 2 deletions src/app/models/home.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use diesel::{Queryable, prelude::Insertable};
use diesel::{prelude::Insertable, Queryable};
use serde::{Deserialize, Serialize};

use crate::schema::homes;
Expand All @@ -9,7 +9,7 @@ use crate::schema::homes;
pub struct Home {
pub id: String,
pub title: String,
pub body: String
pub body: String,
}

/// New user details.
Expand All @@ -19,6 +19,19 @@ pub struct NewHome {
pub body: String,
}

// validations
impl NewHome {
pub fn validate(&self) -> Result<(), String> {
if self.title.trim().is_empty() {
return Err("Name is empty".to_string());
}
if self.body.trim().is_empty() {
return Err("Desciption is empty".to_string());
}
Ok(())
}
}

// impl NewHome {
// /// Constructs new user details from name.
// #[cfg(test)] // only needed in tests
Expand Down
Loading