Skip to content

Commit

Permalink
adjust for work fine
Browse files Browse the repository at this point in the history
  • Loading branch information
ssrlive committed Feb 23, 2024
1 parent 29f5538 commit 8759547
Show file tree
Hide file tree
Showing 12 changed files with 50 additions and 101 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
.VSCodeCounter/
Cargo.lock
target/
temp.db
9 changes: 5 additions & 4 deletions todo_api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
name = "todo_api"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rocket = { version = "0.5", features = ["json"] }
tokio = { version = "1.36", features = ["full"] }
chrono = { version = "0.4", features = ["serde"] }
log = "0.4"
rocket = { version = "0.5", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
surrealdb = { version = "1.2", features = ["kv-mem"] }
serde_json = { version = "1.0" }
surrealdb = { version = "1.2", features = ["kv-rocksdb", "kv-mem"] }
thiserror = "1.0"
tokio = { version = "1.36", features = ["full"] }
18 changes: 8 additions & 10 deletions todo_api/src/db.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::{prelude::W, utils::macros::map};
use crate::utils::macros::map;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, sync::Arc};
use surrealdb::{
dbs::{Response, Session},
kvs::Datastore,
sql::{thing, Array, Object, Value},
sql::{thing, Value},
};

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -66,37 +66,35 @@ impl DB {
Ok(res)
}

pub async fn add_task(&self, title: &str) -> Result<Object, crate::error::Error> {
pub async fn add_task(&self, title: &str) -> Result<serde_json::Value, crate::error::Error> {
let sql = "CREATE tasks SET title = $title, completed = false, created_at = time::now()";
let vars: BTreeMap<String, Value> = map!["title".into() => Value::Strand(title.into())];
let res = self.execute(sql, Some(vars)).await?;

let first_res = res.into_iter().next().expect("Did not get a response");

W(first_res.result?.first()).try_into()
Ok(first_res.result?.into_json())
}

pub async fn get_task(&self, id: &str) -> Result<Object, crate::error::Error> {
pub async fn get_task(&self, id: &str) -> Result<serde_json::Value, crate::error::Error> {
let sql = "SELECT * FROM $th";
let tid = format!("{}", id);
let vars: BTreeMap<String, Value> = map!["th".into() => thing(&tid)?.into()];
let ress = self.execute(sql, Some(vars)).await?;

let first_res = ress.into_iter().next().expect("Did not get a response");

W(first_res.result?.first()).try_into()
Ok(first_res.result?.into_json())
}

pub async fn get_all_tasks(&self) -> Result<Vec<Object>, crate::error::Error> {
pub async fn get_all_tasks(&self) -> Result<serde_json::Value, crate::error::Error> {
let sql = "SELECT * FROM tasks ORDER BY created_at ASC;";

let res = self.execute(sql, None).await?;

let first_res = res.into_iter().next().expect("Did not get a response");

let array: Array = W(first_res.result?).try_into()?;

array.into_iter().map(|value| W(value).try_into()).collect()
Ok(first_res.result?.into_json())
}

pub async fn toggle_task(&self, id: &str) -> Result<AffectedRows, crate::error::Error> {
Expand Down
15 changes: 9 additions & 6 deletions todo_api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Value not of type '{0}'")]
XValueNotOfType(&'static str),

#[error(transparent)]
Surreal(#[from] surrealdb::Error),

#[error(transparent)]
Surrealdb(#[from] surrealdb::error::Db),

#[error(transparent)]
IO(#[from] std::io::Error),
}

impl From<Error> for std::io::Error {
fn from(e: Error) -> std::io::Error {
match e {
Error::IO(e) => e,
_ => std::io::Error::new(std::io::ErrorKind::Other, e.to_string()),
}
}
}
18 changes: 9 additions & 9 deletions todo_api/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,42 @@ use crate::db::{AffectedRows, DB};
use cors::*;
use rocket::{serde::json::Json, State};
use std::{io::ErrorKind, sync::Arc};
use surrealdb::{dbs::Session, kvs::Datastore, sql::Object};
use surrealdb::{dbs::Session, kvs::Datastore, };

mod cors;
mod db;
mod error;
mod prelude;
mod utils;

#[post("/task/<title>")]
async fn add_task(title: &str, db: &State<DB>) -> Result<Json<Object>, std::io::Error> {
async fn add_task(title: &str, db: &State<DB>) -> Result<serde_json::Value, std::io::Error> {
let task = db
.add_task(title)
.await
.map_err(|_| std::io::Error::new(ErrorKind::Other, "Unable to create task."))?;

Ok(Json(task))
log::info!("Task created: {:?}", task.to_string());
Ok(task)
}

#[get("/task/<id>")]
async fn get_task(id: &str, db: &State<DB>) -> Result<Json<Object>, std::io::Error> {
async fn get_task(id: &str, db: &State<DB>) -> Result<serde_json::Value, std::io::Error> {
let task = db
.get_task(id)
.await
.map_err(|_| std::io::Error::new(ErrorKind::Other, "Unable to fetch task."))?;

Ok(Json(task))
Ok(task)
}

#[get("/tasks")]
async fn get_all_tasks(db: &State<DB>) -> Result<Json<Vec<Object>>, std::io::Error> {
async fn get_all_tasks(db: &State<DB>) -> Result<serde_json::Value, std::io::Error> {
let tasks = db
.get_all_tasks()
.await
.map_err(|_| std::io::Error::new(ErrorKind::Other, "Unable to fetch all tasks."))?;

Ok(Json(tasks))
Ok(tasks)
}

#[patch("/task/<id>")]
Expand All @@ -66,7 +66,7 @@ async fn delete_task(id: &str, db: &State<DB>) -> Result<Json<AffectedRows>, std
#[launch]
async fn rocket() -> _ {
let datastore = Arc::new(Datastore::new("memory").await.unwrap());
let session = Session::default().with_ns("my_ns").with_db("my_db");
let session = Session::owner().with_ns("my_ns").with_db("my_db");

let db = DB { datastore, session };

Expand Down
2 changes: 0 additions & 2 deletions todo_api/src/prelude.rs

This file was deleted.

1 change: 0 additions & 1 deletion todo_api/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod macros;
pub mod try_froms;
56 changes: 0 additions & 56 deletions todo_api/src/utils/try_froms.rs

This file was deleted.

9 changes: 4 additions & 5 deletions todo_web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
name = "todo_web"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
wasm-bindgen-futures = "0.4"
web-sys = "0.3"
yew = { version = "0.21", features = ["csr"] }
chrono = { version = "0.4", features = ["serde", "wasmbind"] }
reqwasm = "0.5"
serde = { version = "1.0", features = ["derive"] }
chrono = { version = "0.4", features = ["serde", "wasmbind"] }
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["console"] }
yew = { version = "0.21", features = ["csr"] }
12 changes: 10 additions & 2 deletions todo_web/src/controllers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{
state::{TaskAction, TaskState},
todo_api,
};
use web_sys::{console::log, js_sys::Array, wasm_bindgen::JsValue};
use yew::UseReducerHandle;

pub struct TaskController {
Expand All @@ -16,8 +17,15 @@ impl TaskController {
pub fn init_tasks(&self) {
let tasks = self.state.clone();
wasm_bindgen_futures::spawn_local(async move {
let fetched_tasks = todo_api::fetch_tasks().await.unwrap();
tasks.dispatch(TaskAction::Set(fetched_tasks))
match todo_api::fetch_tasks().await {
Ok(fetched_tasks) => tasks.dispatch(TaskAction::Set(fetched_tasks)),
Err(err) => {
let string = format!("{:?}", err.to_string());
let js_val = JsValue::from_str(&string);
let arr = Array::from(&js_val);
log(&arr);
}
}
});
}

Expand Down
5 changes: 1 addition & 4 deletions todo_web/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ fn app() -> Html {

{
let tasks_controller = tasks_controller.clone();
use_effect_with((), move |_| {
tasks_controller.init_tasks();
|| () // return empty destructor closure
}); // only call on first render
use_effect_with((), move |_| tasks_controller.init_tasks()); // only call on first render
}

let on_create_task = {
Expand Down
5 changes: 3 additions & 2 deletions todo_web/src/todo_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ pub async fn fetch_tasks() -> Result<Vec<Task>, Error> {
}

pub async fn create_task(title: &str) -> Result<Task, Error> {
Request::post(&format!("{BASE_URL}/task/{title}"))
let mut vec: Vec<Task> = Request::post(&format!("{BASE_URL}/task/{title}"))
.send()
.await
.unwrap()
.json()
.await
.await?;
Ok(vec.remove(0))
}

pub async fn toggle_task(id: String) -> Result<AffectedRows, Error> {
Expand Down

0 comments on commit 8759547

Please sign in to comment.