v0.11-updatingP1

This commit is contained in:
2022-11-06 22:21:29 +05:30
parent d0caca5e59
commit dfa83b68b0
3 changed files with 234 additions and 20 deletions

View File

@@ -176,6 +176,7 @@ pub async fn main() {
.route("/api/delete/:id", get(delete_book))
.route("/api/list", get(list_book))
.route("/api/create", post(create_book))
.route("/api/update", post(update_book))
.nest("/images", get_service(ServeDir::new("../images")).handle_error(handle_error))
.merge(SpaRouter::new("/assets", opt.static_dir))
.layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))
@@ -441,3 +442,133 @@ let book: book::Model = book::Model{
"success"
}
async fn update_book(
Extension(ref conn): Extension<DatabaseConnection>,
Json(doc_sent): Json<BookUI>,
) -> impl IntoResponse {
println!("Updating book");
let mut cover = doc_sent.cover.clone();
if !doc_sent.cover.is_none() {
let img_bytes = reqwest::get(cover.unwrap()).await.unwrap().bytes().await.unwrap();
//.expect("Could not fetch image");
//let img_bytes = img_resp.unwrap().bytes();
let image = image::load_from_memory(&img_bytes).unwrap();
let temp_cover = doc_sent.cover.clone().unwrap();
let img_id = temp_cover.split("/").last().unwrap();
image.save(format!("../images/{}",img_id)).expect("Failed to save image");
cover = Some(img_id.to_string());
}
let book: book::Model = book::Model{
open_library_key: doc_sent.open_library_key.to_owned(),
title: (doc_sent.title.to_owned()),
edition_count: doc_sent.edition_count.to_owned(),
first_publish_year: (doc_sent.first_publish_year.to_owned()),
median_page_count: (doc_sent.median_page_count.to_owned()),
goodread_id: doc_sent.goodread_id.to_owned(),
description: doc_sent.description.to_owned(),
comments: doc_sent.comments.to_owned(),
cover: cover.to_owned(),
rating: doc_sent.rating.to_owned(),
time_added: doc_sent.time_added.to_owned(),
id: doc_sent.id.to_owned(),
location: doc_sent.location.to_owned(),
};
let created_book = MutationCore::update_book_by_id(conn, book.id, book)
.await
.expect("could not update book");
MutationCore::delete_book_author(conn, doc_sent.id)
.await
.expect("could not delete book authors while updating");
MutationCore::delete_book_person(conn, doc_sent.id)
.await
.expect("could not delete book persons while updating");
MutationCore::delete_book_place(conn, doc_sent.id)
.await
.expect("could not delete book places while updating");
MutationCore::delete_book_subject(conn, doc_sent.id)
.await
.expect("could not delete book subjects while updating");
MutationCore::delete_book_time(conn, doc_sent.id)
.await
.expect("could not delete book times while updating");
MutationCore::delete_book_isbn(conn, doc_sent.id)
.await
.expect("could not delete book isbns while updating");
for author_name in doc_sent.author_name.as_ref().unwrap().iter() {
let record : book_author::Model = book_author::Model{
id: 1,
book_id: doc_sent.id,
author_name: author_name.to_owned(),
};
MutationCore::create_book_author(conn, record)
.await
.expect("could not create book");
}
for person in doc_sent.person.as_ref().unwrap().iter() {
let record : book_person::Model = book_person::Model{
id: 1,
book_id: doc_sent.id,
person: person.to_owned(),
};
MutationCore::create_book_person(conn, record)
.await
.expect("could not create book");
}
for place in doc_sent.place.as_ref().unwrap().iter() {
let record : book_place::Model = book_place::Model{
id: 1,
book_id: doc_sent.id,
place: place.to_owned(),
};
MutationCore::create_book_place(conn, record)
.await
.expect("could not create book");
}
for subject in doc_sent.subject.as_ref().unwrap().iter() {
let record : book_subject::Model = book_subject::Model{
id: 1,
book_id: doc_sent.id,
subject: subject.to_owned(),
};
MutationCore::create_book_subject(conn, record)
.await
.expect("could not create book");
}
for time in doc_sent.time.as_ref().unwrap().iter() {
let record : book_time::Model = book_time::Model{
id: 1,
book_id: doc_sent.id,
time: time.to_owned(),
};
MutationCore::create_book_time(conn, record)
.await
.expect("could not create book");
}
for isbn in doc_sent.isbn.as_ref().unwrap().iter() {
let record : book_isbn::Model = book_isbn::Model{
id: 1,
book_id: doc_sent.id,
isbn: isbn.to_owned(),
};
MutationCore::create_book_isbn(conn, record)
.await
.expect("could not create book");
}
"success"
}

View File

@@ -107,27 +107,36 @@ impl Mutation {
.save(db)
.await
}
/*
pub async fn update_post_by_id(
pub async fn update_book_by_id(
db: &DbConn,
id: i32,
form_data: post::Model,
) -> Result<post::Model, DbErr> {
let post: post::ActiveModel = Post::find_by_id(id)
form_data: book::Model,
) -> Result<book::Model, DbErr> {
let book: book::ActiveModel = Book::find_by_id(id)
.one(db)
.await?
.ok_or(DbErr::Custom("Cannot find post.".to_owned()))
.ok_or(DbErr::Custom("Cannot find book.".to_owned()))
.map(Into::into)?;
post::ActiveModel {
id: post.id,
book::ActiveModel {
id: book.id,
open_library_key: Set(form_data.open_library_key.to_owned()),
title: Set(form_data.title.to_owned()),
text: Set(form_data.text.to_owned()),
}
.update(db)
.await
edition_count: Set(form_data.edition_count.to_owned()),
first_publish_year: Set(form_data.first_publish_year.to_owned()),
median_page_count: Set(form_data.median_page_count.to_owned()),
goodread_id: Set(form_data.goodread_id.to_owned()),
description: Set(form_data.description.to_owned()),
cover: Set(form_data.cover.to_owned()),
location: Set(form_data.location.to_owned()),
time_added: Set(form_data.time_added.to_owned()),
rating: Set(form_data.rating.to_owned()),
comments: Set(form_data.comments.to_owned()),
}.update(db).await
}
*/
pub async fn delete_book(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
let book: book::ActiveModel = Book::find_by_id(id)
.one(db)
@@ -138,6 +147,53 @@ impl Mutation {
book.delete(db).await
}
pub async fn delete_book_author(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_author::Entity::delete_many().filter(
Condition::any()
.add(book_author::Column::BookId.eq(id))
).exec(db).await
}
pub async fn delete_book_person(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_person::Entity::delete_many().filter(
Condition::any()
.add(book_person::Column::BookId.eq(id))
).exec(db).await
}
pub async fn delete_book_place(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_place::Entity::delete_many().filter(
Condition::any()
.add(book_place::Column::BookId.eq(id))
).exec(db).await
}
pub async fn delete_book_subject(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_subject::Entity::delete_many().filter(
Condition::any()
.add(book_subject::Column::BookId.eq(id))
).exec(db).await
}
pub async fn delete_book_time(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_time::Entity::delete_many().filter(
Condition::any()
.add(book_time::Column::BookId.eq(id))
).exec(db).await
}
pub async fn delete_book_isbn(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_isbn::Entity::delete_many().filter(
Condition::any()
.add(book_isbn::Column::BookId.eq(id))
).exec(db).await
}
pub async fn delete_all_books(db: &DbConn) -> Result<DeleteResult, DbErr> {
Book::delete_many().exec(db).await
}

View File

@@ -50,6 +50,7 @@ pub struct AppState {
pub search: RcSignal<String>,
pub openlibrary: RcSignal<bool>,
pub adding: RcSignal<bool>,
pub updating: RcSignal<bool>,
pub addingbook: RcSignal<BookUI>,
}
@@ -77,6 +78,12 @@ async fn add_book(record: BookUI) -> Result<reqwasm::http::Response, reqwasm::Er
Ok(resp)
}
async fn update_book(record: BookUI) -> Result<reqwasm::http::Response, reqwasm::Error> {
let url = format!("http://localhost:8081/api/update");
let resp = Request::post(&url).body(serde_wasm_bindgen::to_value(&serde_json::to_string(&record).unwrap()).unwrap()).header("content-type","application/json").send().await?;
Ok(resp)
}
async fn delete_book(id: i32) -> Result<reqwasm::http::Response, reqwasm::Error> {
let url = format!("http://localhost:8081/api/delete/{}", id);
let resp = Request::get(&url).send().await?;
@@ -177,8 +184,10 @@ async fn ListDB<G: Html>(cx: Scope<'_>) -> View<G> {
#[component(inline_props)]
pub fn BookDB<G: Html>(cx: Scope, bookitem: BookUIProp) -> View<G> {
let app_state = use_context::<AppState>(cx);
let book = bookitem.bookitem.clone();
let coverurl = book.cover.clone().unwrap_or("http://localhost:8081/images/placeholder.jpg".to_string());
let bookdelete = bookitem.bookitem.clone();
let coverurl = book.cover.clone().unwrap_or("http://localhost:8081/images/placeholder.jpg".to_string());
let handle_delete = move |_| {
spawn_local(async move {
let temp = delete_book(book.id).await.unwrap();
@@ -186,6 +195,12 @@ pub fn BookDB<G: Html>(cx: Scope, bookitem: BookUIProp) -> View<G> {
});
};
let handle_update = move |_| {
app_state.adding.set(false);
app_state.updating.set(true);
app_state.addingbook.set(bookdelete.clone());
};
view! { cx,
div(class="column"){
div(class="card"){
@@ -193,6 +208,8 @@ pub fn BookDB<G: Html>(cx: Scope, bookitem: BookUIProp) -> View<G> {
(format!("{:?}",book))
button(class="delete", on:click=handle_delete){ "-" }
button(class="update", on:click=handle_update){ "=" }
}
}
@@ -316,7 +333,7 @@ info!("Adding book");
let times: Vec<String> = (*inp_time.get()).clone().split(",").map(|x| x.to_string()).collect::<Vec<String>>();
let isbns: Vec<String> = (*inp_isbn.get()).clone().split(",").map(|x| x.to_string()).collect::<Vec<String>>();
let record : BookUI = BookUI{
id: 1,
id: app_state.addingbook.get().id.clone(),
title: (*inp_title.get()).clone(),
open_library_key: Some((*inp_olkey.get()).clone()),
edition_count: Some(inp_editioncount.get().parse::<i32>().unwrap_or(0)),
@@ -337,18 +354,27 @@ info!("Adding book");
isbn: Some(isbns),
};
app_state.adding.set(false);
app_state.addingbook.set(BookUI::default());
if *app_state.updating.get() == false {
spawn_local(async move {
let temp = add_book(record).await.unwrap();
println!("{}",temp.status());
println!("{}",temp.status());
});
} else {
spawn_local(async move {
let temp = update_book(record).await.unwrap();
println!("{}",temp.status());
});
}
app_state.addingbook.set(BookUI::default());
app_state.updating.set(false);
app_state.adding.set(false);
};
view! {cx,
p {
(if *app_state.adding.get() == true {
(if *app_state.adding.get() == true || *app_state.updating.get() == true {
view!{ cx,
input(bind:value=inp_title, placeholder="Title" )
input(bind:value=inp_olkey, placeholder="OpenLibrary Key" )
@@ -385,6 +411,7 @@ fn App<G: Html>(cx: Scope) -> View<G> {
search: create_rc_signal(String::default()),
openlibrary: create_rc_signal(bool::default()),
adding: create_rc_signal(bool::default()),
updating: create_rc_signal(bool::default()),
addingbook: create_rc_signal(BookUI::default()),
};
provide_context(cx, app_state);