Skip to content

Commit

Permalink
add models
Browse files Browse the repository at this point in the history
  • Loading branch information
huangcheng committed Nov 27, 2023
1 parent 6ffea8e commit 0d3885f
Show file tree
Hide file tree
Showing 22 changed files with 145 additions and 36 deletions.
11 changes: 6 additions & 5 deletions migrations/20231125065411_user.up.sql
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
CREATE TABLE user (
username VARCHAR(20) NOT NULL PRIMARY KEY,
nickname VARCHAR(20) NOT NULL,
CREATE TABLE user
(
username VARCHAR(20) NOT NULL PRIMARY KEY,
nickname VARCHAR(20) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
avatar VARCHAR(255) DEFAULT NULL
email VARCHAR(255) NOT NULL,
avatar VARCHAR(255) DEFAULT NULL
);
11 changes: 7 additions & 4 deletions migrations/20231126121150_category.up.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
CREATE TABLE category (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
description VARCHAR(255) NOT NULL
CREATE TABLE category
(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
description VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
1 change: 1 addition & 0 deletions migrations/20231127033035_site.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE site;
10 changes: 10 additions & 0 deletions migrations/20231127033035_site.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE site
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
url VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
icon VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
1 change: 1 addition & 0 deletions migrations/20231127033326_category_site.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE category_site;
5 changes: 5 additions & 0 deletions migrations/20231127033326_category_site.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE TABLE category_site
(
category_id INT NOT NULL REFERENCES category (id),
site_id INT NOT NULL REFERENCES site (id)
);
5 changes: 4 additions & 1 deletion src/bin/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ async fn main() -> Result<(), rocket::Error> {
.mount("/api/user", routes![user::me])
.mount("/api/auth", routes![auth::login, auth::logout])
.mount("/api/categories", routes![category::all])
.mount("/api/category", routes![category::update, category::add, category::delete])
.mount(
"/api/category",
routes![category::update, category::add, category::delete],
)
.launch()
.await?;

Expand Down
1 change: 1 addition & 0 deletions src/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod auth;
pub mod category;
pub mod site;
pub mod user;
41 changes: 26 additions & 15 deletions src/handlers/category.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,39 @@ use sqlx::{query, query_as};
use crate::errors::ServiceError;
use crate::models::category::Category;
use crate::request::category::{CreateCategory, UpdateCategory};
use crate::response;
use crate::state::AppState;

pub async fn get_all_categories(state: &State<AppState>) -> Result<Vec<Category>, ServiceError> {
let categories = sqlx::query_as::<_, Category>(r#"SELECT id, name, description FROM category"#)
.fetch_all(&state.pool)
.await?;
pub async fn get_all_categories(
state: &State<AppState>,
) -> Result<Vec<response::category::Category>, ServiceError> {
let categories = sqlx::query_as::<_, Category>(
r#"SELECT id, name, description, created_at, updated_at FROM category"#,
)
.fetch_all(&state.pool)
.await?;

Ok(categories)
Ok(categories
.into_iter()
.map(|category| category.into())
.collect())
}

pub async fn update_category<'r>(
id: &'r str,
category: &'r UpdateCategory<'r>,
state: &State<AppState>,
) -> Result<Category, ServiceError> {
let record =
query_as::<_, Category>(r#"SELECT id, name, description FROM category WHERE id = ?"#)
.bind(id)
.fetch_one(&state.pool)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::NotFound,
_ => ServiceError::DatabaseError(e.into()),
})?;
let record = query_as::<_, Category>(
r#"SELECT id, name, description, created_at, updated_at FROM category WHERE id = ?"#,
)
.bind(id)
.fetch_one(&state.pool)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::NotFound,
_ => ServiceError::DatabaseError(e),
})?;

let name = match category.name {
Some(name) => String::from(name),
Expand All @@ -43,12 +52,14 @@ pub async fn update_category<'r>(
id: record.id,
name,
description,
created_at: record.created_at,
updated_at: record.updated_at,
};

query(r#"UPDATE category SET name = ?, description = ? WHERE id = ?"#)
.bind(&record.name)
.bind(&record.description)
.bind(&record.id)
.bind(record.id)
.execute(&state.pool)
.await?;

Expand Down
1 change: 1 addition & 0 deletions src/handlers/site.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

2 changes: 2 additions & 0 deletions src/models.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
pub mod category;
pub(crate) mod category_site;
pub mod site;
pub mod user;
3 changes: 3 additions & 0 deletions src/models/category.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

Expand All @@ -6,4 +7,6 @@ pub struct Category {
pub id: i64,
pub name: String,
pub description: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
8 changes: 8 additions & 0 deletions src/models/category_site.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct CategorySite {
pub category_id: i64,
pub site_id: i64,
}
14 changes: 14 additions & 0 deletions src/models/site.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct Site {
pub id: i64,
pub name: String,
pub url: String,
pub description: String,
pub icon: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
1 change: 1 addition & 0 deletions src/request.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod auth;
pub mod category;
pub mod site;
6 changes: 6 additions & 0 deletions src/request/site.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct CreateCategory<'r> {
pub name: &'r str,
pub description: &'r str,
}
1 change: 1 addition & 0 deletions src/response.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod auth;
pub mod category;
pub mod site;
pub mod user;
19 changes: 19 additions & 0 deletions src/response/category.rs
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
use serde::Serialize;

use crate::models::category;

#[derive(Debug, Serialize)]
pub struct Category {
pub id: i64,
pub name: String,
pub description: String,
}

impl From<category::Category> for Category {
fn from(category: category::Category) -> Self {
Self {
id: category.id,
name: category.name,
description: category.description,
}
}
}
1 change: 1 addition & 0 deletions src/response/site.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions src/routes.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod auth;
pub mod category;
pub mod site;
pub mod user;
37 changes: 26 additions & 11 deletions src/routes/category.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
use std::ops::Deref;

use log::error;
use rocket::http::Status;
use rocket::serde::json::Json;
use rocket::State;
use rocket::{get, post, put, delete};
use rocket::{delete, get, post, put};

use crate::handlers::category::{add_category, get_all_categories, update_category, delete_category};
use crate::handlers::category::{
add_category, delete_category, get_all_categories, update_category,
};
use crate::middlewares::JwtMiddleware;
use crate::models::category::Category;
use crate::request::category::{CreateCategory, UpdateCategory};
use crate::response::category::Category;
use crate::state::AppState;

#[get("/")]
pub async fn all(state: &State<AppState>) -> Result<Json<Vec<Category>>, Status> {
let categories = get_all_categories(state).await.map_err(|e| e.status())?;
let categories = get_all_categories(state).await.map_err(|e| {
error!("{}", e);

e.status()
})?;

Ok(Json(categories))
}
Expand All @@ -27,7 +34,11 @@ pub async fn update<'r>(
) -> Result<(), Status> {
update_category(id, category.deref(), state)
.await
.map_err(|e| e.status())?;
.map_err(|e| {
error!("{}", e);

e.status()
})?;

Ok(())
}
Expand All @@ -38,9 +49,11 @@ pub async fn add<'r>(
state: &State<AppState>,
_jwt: JwtMiddleware,
) -> Result<(), Status> {
add_category(category.deref(), state)
.await
.map_err(|e| e.status())?;
add_category(category.deref(), state).await.map_err(|e| {
error!("{}", e);

e.status()
})?;

Ok(())
}
Expand All @@ -51,9 +64,11 @@ pub async fn delete<'r>(
state: &State<AppState>,
_jwt: JwtMiddleware,
) -> Result<(), Status> {
delete_category(id, state)
.await
.map_err(|e| e.status())?;
delete_category(id, state).await.map_err(|e| {
error!("{}", e);

e.status()
})?;

Ok(())
}
1 change: 1 addition & 0 deletions src/routes/site.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

0 comments on commit 0d3885f

Please sign in to comment.