|
| 1 | +use async_trait::async_trait; |
| 2 | +use serde::{Deserialize, Serialize}; |
| 3 | +use silent::prelude::*; |
| 4 | +use std::collections::HashMap; |
| 5 | +use std::sync::{Arc, RwLock}; |
| 6 | +use uuid::Uuid; |
| 7 | + |
| 8 | +fn main() { |
| 9 | + logger::fmt().init(); |
| 10 | + let db = Db::default(); |
| 11 | + let middle_ware = MiddleWare { db }; |
| 12 | + let route = Route::new("todos") |
| 13 | + .hook(middle_ware) |
| 14 | + .get(todos_index) |
| 15 | + .post(todos_create) |
| 16 | + .append( |
| 17 | + Route::new("<id:uuid>") |
| 18 | + .patch(todos_update) |
| 19 | + .delete(todos_delete), |
| 20 | + ); |
| 21 | + Server::new().bind_route(route).run(); |
| 22 | +} |
| 23 | + |
| 24 | +struct MiddleWare { |
| 25 | + db: Db, |
| 26 | +} |
| 27 | + |
| 28 | +#[async_trait] |
| 29 | +impl Handler for MiddleWare { |
| 30 | + async fn middleware_call( |
| 31 | + &self, |
| 32 | + req: &mut Request, |
| 33 | + _res: &mut Response, |
| 34 | + ) -> Result<(), SilentError> { |
| 35 | + req.extensions_mut().insert(self.db.clone()); |
| 36 | + Ok(()) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +#[derive(Debug, Deserialize, Default)] |
| 41 | +pub struct Pagination { |
| 42 | + pub offset: Option<usize>, |
| 43 | + pub limit: Option<usize>, |
| 44 | +} |
| 45 | + |
| 46 | +async fn todos_index(mut req: Request) -> Result<Vec<Todo>, SilentError> { |
| 47 | + let pagination = req.params_parse::<Pagination>()?; |
| 48 | + |
| 49 | + let db = req.extensions().get::<Db>().unwrap(); |
| 50 | + let todos = db.read().unwrap(); |
| 51 | + |
| 52 | + let todos = todos |
| 53 | + .values() |
| 54 | + .skip(pagination.offset.unwrap_or(0)) |
| 55 | + .take(pagination.limit.unwrap_or(usize::MAX)) |
| 56 | + .cloned() |
| 57 | + .collect::<Vec<_>>(); |
| 58 | + |
| 59 | + Ok(todos) |
| 60 | +} |
| 61 | + |
| 62 | +#[derive(Debug, Deserialize)] |
| 63 | +struct CreateTodo { |
| 64 | + text: String, |
| 65 | +} |
| 66 | + |
| 67 | +async fn todos_create(mut req: Request) -> Result<Todo, SilentError> { |
| 68 | + let create_todo = req.json_parse::<CreateTodo>().await?; |
| 69 | + let db = req.extensions().get::<Db>().unwrap(); |
| 70 | + |
| 71 | + let todo = Todo { |
| 72 | + id: Uuid::new_v4(), |
| 73 | + text: create_todo.text, |
| 74 | + completed: false, |
| 75 | + }; |
| 76 | + |
| 77 | + db.write().unwrap().insert(todo.id, todo.clone()); |
| 78 | + |
| 79 | + Ok(todo) |
| 80 | +} |
| 81 | + |
| 82 | +#[derive(Debug, Deserialize)] |
| 83 | +struct UpdateTodo { |
| 84 | + text: Option<String>, |
| 85 | + completed: Option<bool>, |
| 86 | +} |
| 87 | + |
| 88 | +async fn todos_update(mut req: Request) -> Result<Todo, SilentError> { |
| 89 | + let input = req.json_parse::<UpdateTodo>().await?; |
| 90 | + let db = req.extensions().get::<Db>().unwrap(); |
| 91 | + let id = req.get_path_params("id").unwrap(); |
| 92 | + if let PathParam::UUid(id) = id { |
| 93 | + let todo = db.read().unwrap().get(id).cloned(); |
| 94 | + |
| 95 | + if todo.is_none() { |
| 96 | + return Err(SilentError::BusinessError { |
| 97 | + code: StatusCode::NOT_FOUND, |
| 98 | + msg: "Not Found".to_string(), |
| 99 | + }); |
| 100 | + } |
| 101 | + |
| 102 | + let mut todo = todo.unwrap(); |
| 103 | + |
| 104 | + if let Some(text) = input.text { |
| 105 | + todo.text = text; |
| 106 | + } |
| 107 | + |
| 108 | + if let Some(completed) = input.completed { |
| 109 | + todo.completed = completed; |
| 110 | + } |
| 111 | + |
| 112 | + db.write().unwrap().insert(todo.id, todo.clone()); |
| 113 | + |
| 114 | + Ok(todo) |
| 115 | + } else { |
| 116 | + Err(SilentError::BusinessError { |
| 117 | + code: StatusCode::NOT_FOUND, |
| 118 | + msg: "Not Found".to_string(), |
| 119 | + }) |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +async fn todos_delete(req: Request) -> Result<(), SilentError> { |
| 124 | + let db = req.extensions().get::<Db>().unwrap(); |
| 125 | + let id = req.get_path_params("id").unwrap(); |
| 126 | + if let PathParam::UUid(id) = id { |
| 127 | + if db.write().unwrap().remove(id).is_some() { |
| 128 | + Ok(()) |
| 129 | + } else { |
| 130 | + Err(SilentError::BusinessError { |
| 131 | + code: StatusCode::NOT_FOUND, |
| 132 | + msg: "Not Found".to_string(), |
| 133 | + }) |
| 134 | + } |
| 135 | + } else { |
| 136 | + Err(SilentError::BusinessError { |
| 137 | + code: StatusCode::NOT_FOUND, |
| 138 | + msg: "Not Found".to_string(), |
| 139 | + }) |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +type Db = Arc<RwLock<HashMap<Uuid, Todo>>>; |
| 144 | + |
| 145 | +#[derive(Debug, Serialize, Deserialize, Clone)] |
| 146 | +struct Todo { |
| 147 | + id: Uuid, |
| 148 | + text: String, |
| 149 | + completed: bool, |
| 150 | +} |
0 commit comments