Skip to content

Commit 9af4abf

Browse files
committed
adjust for work fine
1 parent 29f5538 commit 9af4abf

File tree

13 files changed

+51
-107
lines changed

13 files changed

+51
-107
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
.VSCodeCounter/
33
Cargo.lock
44
target/
5+
temp.db

todo_api/Cargo.toml

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
name = "todo_api"
33
version = "0.1.0"
44
edition = "2021"
5-
65
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
76

87
[dependencies]
9-
rocket = { version = "0.5", features = ["json"] }
10-
tokio = { version = "1.36", features = ["full"] }
118
chrono = { version = "0.4", features = ["serde"] }
9+
log = "0.4"
10+
rocket = { version = "0.5", features = ["json"] }
1211
serde = { version = "1.0", features = ["derive"] }
13-
surrealdb = { version = "1.2", features = ["kv-mem"] }
12+
serde_json = { version = "1.0" }
13+
surrealdb = { version = "1.2", features = ["kv-rocksdb", "kv-mem"] }
1414
thiserror = "1.0"
15+
tokio = { version = "1.36", features = ["full"] }

todo_api/src/db.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
use crate::{prelude::W, utils::macros::map};
1+
use crate::utils::macros::map;
22
use chrono::{DateTime, Utc};
33
use serde::{Deserialize, Serialize};
44
use std::{collections::BTreeMap, sync::Arc};
55
use surrealdb::{
66
dbs::{Response, Session},
77
kvs::Datastore,
8-
sql::{thing, Array, Object, Value},
8+
sql::{thing, Value},
99
};
1010

1111
#[derive(Debug, Serialize, Deserialize)]
@@ -66,37 +66,35 @@ impl DB {
6666
Ok(res)
6767
}
6868

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

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

76-
W(first_res.result?.first()).try_into()
76+
Ok(first_res.result?.into_json())
7777
}
7878

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

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

87-
W(first_res.result?.first()).try_into()
87+
Ok(first_res.result?.into_json())
8888
}
8989

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

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

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

97-
let array: Array = W(first_res.result?).try_into()?;
98-
99-
array.into_iter().map(|value| W(value).try_into()).collect()
97+
Ok(first_res.result?.into_json())
10098
}
10199

102100
pub async fn toggle_task(&self, id: &str) -> Result<AffectedRows, crate::error::Error> {

todo_api/src/error.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,18 @@
22

33
#[derive(thiserror::Error, Debug)]
44
pub enum Error {
5-
#[error("Value not of type '{0}'")]
6-
XValueNotOfType(&'static str),
7-
8-
#[error(transparent)]
9-
Surreal(#[from] surrealdb::Error),
10-
115
#[error(transparent)]
126
Surrealdb(#[from] surrealdb::error::Db),
137

148
#[error(transparent)]
159
IO(#[from] std::io::Error),
1610
}
11+
12+
impl From<Error> for std::io::Error {
13+
fn from(e: Error) -> std::io::Error {
14+
match e {
15+
Error::IO(e) => e,
16+
_ => std::io::Error::new(std::io::ErrorKind::Other, e.to_string()),
17+
}
18+
}
19+
}

todo_api/src/main.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,42 +5,42 @@ use crate::db::{AffectedRows, DB};
55
use cors::*;
66
use rocket::{serde::json::Json, State};
77
use std::{io::ErrorKind, sync::Arc};
8-
use surrealdb::{dbs::Session, kvs::Datastore, sql::Object};
8+
use surrealdb::{dbs::Session, kvs::Datastore, };
99

1010
mod cors;
1111
mod db;
1212
mod error;
13-
mod prelude;
1413
mod utils;
1514

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

23-
Ok(Json(task))
22+
log::info!("Task created: {:?}", task.to_string());
23+
Ok(task)
2424
}
2525

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

33-
Ok(Json(task))
33+
Ok(task)
3434
}
3535

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

43-
Ok(Json(tasks))
43+
Ok(tasks)
4444
}
4545

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

7171
let db = DB { datastore, session };
7272

todo_api/src/prelude.rs

Lines changed: 0 additions & 2 deletions
This file was deleted.

todo_api/src/utils/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
pub mod macros;
2-
pub mod try_froms;

todo_api/src/utils/try_froms.rs

Lines changed: 0 additions & 56 deletions
This file was deleted.

todo_web/Cargo.toml

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22
name = "todo_web"
33
version = "0.1.0"
44
edition = "2021"
5-
65
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
76

87
[dependencies]
9-
wasm-bindgen-futures = "0.4"
10-
web-sys = "0.3"
11-
yew = { version = "0.21", features = ["csr"] }
8+
chrono = { version = "0.4", features = ["serde", "wasmbind"] }
129
reqwasm = "0.5"
1310
serde = { version = "1.0", features = ["derive"] }
14-
chrono = { version = "0.4", features = ["serde", "wasmbind"] }
11+
wasm-bindgen-futures = "0.4"
12+
web-sys = { version = "0.3", features = ["console"] }
13+
yew = { version = "0.21", features = ["csr"] }

todo_web/src/controllers.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::{
22
state::{TaskAction, TaskState},
33
todo_api,
44
};
5+
use web_sys::{js_sys::Array, wasm_bindgen::JsValue};
56
use yew::UseReducerHandle;
67

78
pub struct TaskController {
@@ -16,8 +17,15 @@ impl TaskController {
1617
pub fn init_tasks(&self) {
1718
let tasks = self.state.clone();
1819
wasm_bindgen_futures::spawn_local(async move {
19-
let fetched_tasks = todo_api::fetch_tasks().await.unwrap();
20-
tasks.dispatch(TaskAction::Set(fetched_tasks))
20+
match todo_api::fetch_tasks().await {
21+
Ok(fetched_tasks) => tasks.dispatch(TaskAction::Set(fetched_tasks)),
22+
Err(err) => {
23+
let string = format!("{:?}", err.to_string());
24+
let js_val = JsValue::from_str(&string);
25+
let arr = Array::from(&js_val);
26+
web_sys::console::log(&arr);
27+
}
28+
}
2129
});
2230
}
2331

0 commit comments

Comments
 (0)