Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(problem): list all problems from specific user #8

Merged
merged 1 commit into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changes/list-problem.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"algohub-server": patch:feat
---

Add method for listing all problems from specific user.
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.

5 changes: 0 additions & 5 deletions src/models/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,3 @@ pub struct Session {
pub account_id: Thing,
pub token: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
id: Option<Thing>,
}
8 changes: 2 additions & 6 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use serde::Serialize;

pub mod account;
pub mod error;
pub mod problem;
pub mod response;
pub mod shared;

#[derive(Serialize)]
pub struct UpdateAt {
pub updated_at: chrono::NaiveDateTime,
}
pub use shared::*;
2 changes: 1 addition & 1 deletion src/models/problem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl From<ProblemData<'_>> for Problem {
}
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug)]
pub struct ProblemDetail {
pub id: Thing,

Expand Down
19 changes: 19 additions & 0 deletions src/models/shared.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
id: Option<Thing>,
}

#[derive(Serialize)]
pub struct UpdateAt {
pub updated_at: chrono::NaiveDateTime,
}

#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct Credential<'c> {
pub id: &'c str,
pub token: &'c str,
}
3 changes: 2 additions & 1 deletion src/routes/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ use surrealdb::{engine::remote::ws::Client, Surreal};

use crate::{
models::{
account::{Profile, Record},
account::Profile,
error::{Error, ErrorResponse},
response::{Empty, Response},
Record,
},
utils::{account, session},
Result,
Expand Down
26 changes: 24 additions & 2 deletions src/routes/problem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::{
error::Error,
problem::{Mode, Problem, ProblemDetail, Sample},
response::Response,
Credential,
},
utils::{problem, session},
Result,
Expand Down Expand Up @@ -50,7 +51,7 @@ pub struct ProblemData<'r> {
pub private: bool,
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
pub struct ProblemResponse {
pub id: String,
Expand Down Expand Up @@ -128,6 +129,27 @@ pub async fn get(
}))
}

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

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

Ok(Json(Response {
success: true,
message: "Problems found".to_string(),
data: Some(problems),
}))
}

#[derive(Serialize, Deserialize)]
pub struct SubmitData<'r> {
pub id: &'r str,
Expand Down Expand Up @@ -234,5 +256,5 @@ pub async fn submit(

pub fn routes() -> Vec<rocket::Route> {
use rocket::routes;
routes![create, get, submit]
routes![create, get, submit, list]
}
11 changes: 11 additions & 0 deletions src/utils/problem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,14 @@ where
{
Ok(db.select(("problem", id)).await?)
}

pub async fn list<M>(db: &Surreal<Client>, id: &str) -> Result<Vec<M>>
where
for<'de> M: Deserialize<'de>,
{
Ok(db
.query("SELECT * FROM problem WHERE owner = type::thing(\"account\", $id)")
.bind(("id", id.to_string()))
.await?
.take(0)?)
}
115 changes: 115 additions & 0 deletions tests/problem.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
use algohub_server::{
models::{
problem::{Mode, ProblemDetail},
response::{Empty, Response},
Credential,
},
routes::{
account::{Authenticate, RegisterData, RegisterResponse},
problem::{ProblemData, ProblemResponse},
},
};
use anyhow::Result;
use rocket::local::asynchronous::Client;

#[rocket::async_test]
async fn test_problem() -> Result<()> {
let rocket = algohub_server::rocket().await;

let client = Client::tracked(rocket).await?;

println!("Testing register...");
let response = client
.post("/account/create")
.json(&RegisterData {
username: "fu050409".to_string(),
password: "password".to_string(),
email: "[email protected]".to_string(),
})
.dispatch()
.await;

assert_eq!(response.status().code, 200);

let Response {
success,
message: _,
data,
} = response.into_json().await.unwrap();
let data: RegisterResponse = data.unwrap();

let id = data.id.clone();
let token = data.token.clone();

assert!(success);
println!("Registered account: {:?}", &data);

for i in 0..10 {
let response = client
.post("/problem/create")
.json(&ProblemData {
id: &id,
token: &token,
title: &format!("Test Problem #{}", i),
description: "Test Description".to_string(),
input: Some("Test Input".to_string()),
output: Some("Test Output".to_string()),
samples: vec![],
hint: None,

time_limit: 1000,
memory_limit: 128,
test_cases: vec![],
categories: vec![],
tags: vec![],
mode: Mode::ICPC,
private: true,
})
.dispatch()
.await;

assert_eq!(response.status().code, 200);

let Response {
success,
message: _,
data,
} = response.into_json().await.unwrap();
let data: ProblemResponse = data.unwrap();

assert!(success);
println!("Created problem: {:?}", &data);
}

let response = client
.post("/problem/list")
.json(&Credential {
id: &id,
token: &token,
})
.dispatch()
.await;

let Response {
success,
message: _,
data,
} = response
.into_json::<Response<Vec<ProblemDetail>>>()
.await
.unwrap();
let data = data.unwrap();
assert!(success);
assert_eq!(data.len(), 10);

client
.post(format!("/account/delete/{}", id))
.json(&Authenticate { token: &token })
.dispatch()
.await
.into_json::<Response<Empty>>()
.await
.unwrap();

Ok(())
}