Skip to content

Commit

Permalink
feat: create category
Browse files Browse the repository at this point in the history
  • Loading branch information
K0nnyaku committed Nov 29, 2024
1 parent b7a75d9 commit 3a6c43b
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 1 deletion.
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.

19 changes: 19 additions & 0 deletions src/models/category.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 Category {
id: String,
owner: Thing,
name: String,

pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
}


#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct CreateOrganization {
pub name: String,
}
51 changes: 51 additions & 0 deletions src/routes/category.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use crate::{
models::{
category::Category,
error::Error,
response::{Empty, Response},
},
utils::{category, session},
Result,
};
use surrealdb::{engine::remote::ws::Client, Surreal};

#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct CatData {
pub id: &'r str,
pub token: &'r str,

pub cat: Category,
}

#[derive(Serialize, Deserialize)]
pub struct CreateCatResponse {
pub id: String,
pub group: String,
}

#[post("/category", data = "<category>")]
pub async fn create(
db: &State<Surreal<Client>>,
category: Json<CatData<'_>>,
) -> Result<CreateCatResponse> {
if !session::verify(db, category.id, category.token).await {
return Err(Error::Unauthorized(Json(
"Failed to grant permission".into(),
)));
}

let cat = category::create(db, category.id, category.into_inner().cat)
.await
.map_err(|e| Error::ServerError(Json(e.to_string().into())))?
.ok_or(Error::ServerError(Json("Failed to create category".into(),
)))?;

Ok(Json(Response {
success: true,
message: "Category created successfully".into(),
data: Some(CreateCatResponse {
id: cat.id.unwrap().id.to_string(),
}),
}))
}
19 changes: 19 additions & 0 deletions src/utils/category.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use anyhow::Result;
use crate::models::category::{Category, CreateCategory};

pub async fn create(
db: &Surreal<Client>,
id: &str,
cat: CreateCategory,
) -> Result<Option<Category>> {
Ok(db
.create("category")
.content(category {
id: None,
name: cat.name,
owner: (cat.group, id).into(),
created_at: chrono::Local::now().naive_local(),
updated_at: chrono::Local::now().naive_local(),
})
.await?)
}

0 comments on commit 3a6c43b

Please sign in to comment.