Skip to content

Commit

Permalink
refactor(problem): list method for account owns
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 committed Nov 28, 2024
1 parent e28b7a2 commit 0bfdce6
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 38 deletions.
5 changes: 5 additions & 0 deletions .changes/refactor-list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"algohub-server": patch:refactor
---

Refactored `list` method for account owned problems.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 13 additions & 13 deletions src/routes/problem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,33 +129,33 @@ pub async fn get(
}))
}

#[derive(Serialize, Deserialize, Default)]
#[serde(crate = "rocket::serde")]
pub struct ProblemFilter {
pub limit: Option<u8>,
}

#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct ListProblem {
pub auth: OwnedCredentials,
pub filter: Option<ProblemFilter>,
pub id: Option<String>,
pub auth: Option<OwnedCredentials>,
pub limit: Option<u32>,
}

#[post("/list", data = "<data>")]
pub async fn list(
db: &State<Surreal<Client>>,
data: Json<ListProblem>,
) -> Result<Vec<ProblemDetail>> {
if !session::verify(db, &data.auth.id, &data.auth.token).await {
return Err(Error::Unauthorized(Json("Invalid token".into())));
}
let authed_id = if let Some(auth) = &data.auth {
if !session::verify(db, &auth.id, &auth.token).await {
return Err(Error::Unauthorized(Json("Invalid token".into())));
};
Some(auth.id.clone())
} else {
None
};

let data = data.into_inner();
let problems = problem::list(db, &data.auth.id, data.filter)

let problems = problem::list_for_account(db, data.id, authed_id, data.limit)
.await
.map_err(|e| Error::ServerError(Json(e.to_string().into())))?;
println!("{:?}", problems);

Ok(Json(Response {
success: true,
Expand Down
46 changes: 29 additions & 17 deletions src/utils/problem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ use anyhow::Result;
use serde::Deserialize;
use surrealdb::{engine::remote::ws::Client, Surreal};

use crate::{
models::problem::Problem,
routes::problem::{ProblemData, ProblemFilter},
};
use crate::{models::problem::Problem, routes::problem::ProblemData};

pub async fn create(db: &Surreal<Client>, problem: ProblemData<'_>) -> Result<Option<Problem>> {
Ok(db
Expand Down Expand Up @@ -35,24 +32,39 @@ where
Ok(db.select(("problem", id)).await?)
}

pub async fn list<M>(
const LIST_QUERY: &str = r#"
IF $authed THEN
IF $limit THEN
SELECT * FROM problem WHERE owner = type::thing("account", $id) LIMIT $limit
ELSE
SELECT * FROM problem WHERE owner = type::thing("account", $id)
END;
ELSE
IF $limit THEN
SELECT * FROM problem WHERE owner = type::thing("account", $id) AND private = false LIMIT $limit
ELSE
SELECT * FROM problem WHERE owner = type::thing("account", $id) AND private = false
END;
END;"#;

pub async fn list_for_account<M>(
db: &Surreal<Client>,
id: &str,
filter: Option<ProblemFilter>,
account_id: Option<String>,
authed_id: Option<String>,
limit: Option<u32>,
) -> Result<Vec<M>>
where
for<'de> M: Deserialize<'de>,
{
let filter = filter.unwrap_or(ProblemFilter::default());
let mut response = if let Some(limit) = filter.limit {
db.query("SELECT * FROM problem WHERE owner = type::thing(\"account\", $id) LIMIT $limit")
.bind(("id", id.to_string()))
.bind(("limit", limit))
} else {
db.query("SELECT * FROM problem WHERE owner = type::thing(\"account\", $id)")
.bind(("id", id.to_string()))
}
.await?;
let mut response = db
.query(LIST_QUERY)
.bind((
"authed",
authed_id.is_some() && account_id.is_some() && authed_id == account_id,
))
.bind(("id", account_id))
.bind(("limit", limit))
.await?;

Ok(response.take(0)?)
}
16 changes: 9 additions & 7 deletions tests/problem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use algohub_server::{
},
routes::{
account::{RegisterData, RegisterResponse},
problem::{ListProblem, ProblemData, ProblemFilter, ProblemResponse},
problem::{ListProblem, ProblemData, ProblemResponse},
},
};
use anyhow::Result;
Expand Down Expand Up @@ -84,11 +84,12 @@ async fn test_problem() -> Result<()> {
let response = client
.post("/problem/list")
.json(&ListProblem {
auth: OwnedCredentials {
id: Some(id.clone()),
auth: Some(OwnedCredentials {
id: id.clone(),
token: token.clone(),
},
filter: None,
}),
limit: None,
})
.dispatch()
.await;
Expand All @@ -108,11 +109,12 @@ async fn test_problem() -> Result<()> {
let response = client
.post("/problem/list")
.json(&ListProblem {
auth: OwnedCredentials {
id: Some(id.clone()),
auth: Some(OwnedCredentials {
id: id.clone(),
token: token.clone(),
},
filter: Some(ProblemFilter { limit: Some(3) }),
}),
limit: Some(3),
})
.dispatch()
.await;
Expand Down

0 comments on commit 0bfdce6

Please sign in to comment.