Skip to content

Commit

Permalink
Added storing volume details in local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
rimutaka committed Jul 16, 2024
1 parent 50ff7e6 commit 9c42512
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 4 deletions.
2 changes: 2 additions & 0 deletions isbn_wasm_mod/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ console_error_panic_hook = { version = "0.1.7", optional = true }
# compared to the default allocator's ~10K. It is slower than the default
# allocator, however.
wee_alloc = { version = "0.4.5", optional = true }
chrono = { version = "0.4.38", features = ["serde"] }

[dependencies.web-sys]
version = "0.3"
Expand All @@ -44,6 +45,7 @@ features = [
'RequestInit',
'RequestMode',
'Response',
"Storage",
]

[dev-dependencies]
Expand Down
10 changes: 10 additions & 0 deletions isbn_wasm_mod/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use storage::BookRecord;
use utils::{WasmResponse, WasmResult};
use wasm_bindgen::prelude::*;
use web_sys::Window;

pub mod google;
pub mod storage;
#[macro_use]
pub(crate) mod utils;

Expand Down Expand Up @@ -97,6 +99,14 @@ pub async fn get_book_data(isbn: String) {
// log!("{:?}", resp);

report_progress(resp.to_string());

// store the book record in the local storage, if possible
if let Some(Ok(v)) = resp.google_books {
log!("Storing book in local storage");
if let Some(v) = BookRecord::from_google_books(v, &isbn) {
v.add_note(&runtime, "Book scanned".to_string());
}
}
}

/// All error handling in this crate is based on either retrying a request after some time
Expand Down
99 changes: 99 additions & 0 deletions isbn_wasm_mod/src/storage.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use crate::google::Volumes;
use crate::utils::log;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use web_sys::Window;

#[derive(Deserialize, Serialize, Debug)]
pub struct BookNote {
pub timestamp: DateTime<Utc>,
pub note: String,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct BookRecord {
pub isbn: String,
pub title: String,
pub author: String,
pub notes: Vec<BookNote>,
}

#[derive(Deserialize, Serialize, Debug)]
struct BookDB {
books: Vec<BookRecord>,
}

impl BookRecord {
/// Adds a not to an existing book record, creates a new record if the ISBN is not found.
/// The book record is stored in the local storage (front-end only access).
/// Fails silently if the record cannot be stored.
/// TODO: Add error handling.
pub(crate) fn add_note(self, runtime: &Window, note: String) {
// get the book record from the database

let ls = match runtime.local_storage() {
Ok(Some(v)) => v,
Err(e) => {
log!("Failed to get local storage: {:?}", e);
return;
}
_ => {
log!("Local storage not available (OK(None))");
return;
}
};

let mut book_record = match ls.get_item(&self.isbn) {
Ok(Some(v)) => match serde_json::from_str::<BookRecord>(&v) {
Ok(v) => v,
Err(e) => {
log!("Failed to parse local storage book record: {:?}", e);
return;
}
},
Ok(None) => {
log!("Book record not found in local storage");
self
}
Err(e) => {
log!("Failed to get book record from local storage: {:?}", e);
return;
}
};

// add the note to the book record
book_record.notes.push(BookNote {
timestamp: Utc::now(),
note,
});

// replace the record in the database
let isbn = book_record.isbn.clone();
let book_record = match serde_json::to_string(&book_record) {
Ok(v) => v,
Err(e) => {
log!("Failed to serialize book record: {:?}", e);
return;
}
};
match ls.set_item(&isbn, &book_record) {
Ok(()) => log!("Book record updated"),
Err(e) => log!("Failed to update book record: {:?}", e),
}
}

/// Converts the very first Volume into Self, if it exists.
/// Otherwise, returns None.
pub(crate) fn from_google_books(volumes: Volumes, isbn: &str) -> Option<Self> {
if volumes.items.is_empty() {
return None;
}

Some(Self {
isbn: isbn.to_string(),
title: volumes.items[0].volume_info.title.clone(),
author: volumes.items[0].volume_info.authors[0].clone(),
notes: Vec::new(),
})
}
}
30 changes: 26 additions & 4 deletions src/wasm-rust/isbn_mod.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ function handleError(f, args) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
}
function __wbg_adapter_100(arg0, arg1, arg2, arg3) {
function __wbg_adapter_110(arg0, arg1, arg2, arg3) {
_assertNum(arg0);
_assertNum(arg1);
wasm.wasm_bindgen__convert__closures__invoke2_mut__h7e0de6a9770ded74(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
Expand Down Expand Up @@ -471,6 +471,10 @@ function __wbg_get_imports() {
_assertBoolean(ret);
return ret;
}, arguments) };
imports.wbg.__wbg_localStorage_e381d34d0c40c761 = function() { return handleError(function (arg0) {
const ret = getObject(arg0).localStorage;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_fetch_c4b6afebdb1f918e = function() { return logError(function (arg0, arg1) {
const ret = getObject(arg0).fetch(getObject(arg1));
return addHeapObject(ret);
Expand Down Expand Up @@ -504,6 +508,16 @@ function __wbg_get_imports() {
const ret = getObject(arg0).json();
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_getItem_164e8e5265095b87 = function() { return handleError(function (arg0, arg1, arg2, arg3) {
const ret = getObject(arg1).getItem(getStringFromWasm0(arg2, arg3));
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len1;
getInt32Memory0()[arg0 / 4 + 0] = ptr1;
}, arguments) };
imports.wbg.__wbg_setItem_ba2bb41d73dac079 = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).setItem(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
}, arguments) };
imports.wbg.__wbg_get_bd8e338fbd5f5cc8 = function() { return logError(function (arg0, arg1) {
const ret = getObject(arg0)[arg1 >>> 0];
return addHeapObject(ret);
Expand Down Expand Up @@ -563,6 +577,14 @@ function __wbg_get_imports() {
_assertBoolean(ret);
return ret;
}, arguments) };
imports.wbg.__wbg_getTime_2bc4375165f02d15 = function() { return logError(function (arg0) {
const ret = getObject(arg0).getTime();
return ret;
}, arguments) };
imports.wbg.__wbg_new0_7d84e5b2cd9fdc73 = function() { return logError(function () {
const ret = new Date();
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_new_72fb9a18b5ae2624 = function() { return logError(function () {
const ret = new Object();
return addHeapObject(ret);
Expand All @@ -578,7 +600,7 @@ function __wbg_get_imports() {
const a = state0.a;
state0.a = 0;
try {
return __wbg_adapter_100(a, state0.b, arg0, arg1);
return __wbg_adapter_110(a, state0.b, arg0, arg1);
} finally {
state0.a = a;
}
Expand Down Expand Up @@ -679,8 +701,8 @@ function __wbg_get_imports() {
const ret = wasm.memory;
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper896 = function() { return logError(function (arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 61, __wbg_adapter_44);
imports.wbg.__wbindgen_closure_wrapper1296 = function() { return logError(function (arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 80, __wbg_adapter_44);
return addHeapObject(ret);
}, arguments) };

Expand Down
Binary file modified src/wasm-rust/isbn_mod_bg.wasm
Binary file not shown.

0 comments on commit 9c42512

Please sign in to comment.