Files
axum/examples/todos/src/main.rs
T

168 lines
4.2 KiB
Rust
Raw Normal View History

2021-07-22 15:38:32 +02:00
//! Provides a RESTful web server managing some Todos.
//!
//! API will be:
//!
//! - `GET /todos`: return a JSON list of Todos.
//! - `POST /todos`: create a new Todo.
//! - `PUT /todos/:id`: update a specific Todo.
//! - `DELETE /todos/:id`: delete a specific Todo.
2021-08-02 23:09:09 +02:00
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-todos
2021-08-02 23:09:09 +02:00
//! ```
2021-07-22 15:38:32 +02:00
use axum::{
2021-10-24 19:33:03 +02:00
error_handling::HandleErrorLayer,
2021-08-18 00:04:15 +02:00
extract::{Extension, Path, Query},
http::StatusCode,
2021-07-22 15:38:32 +02:00
response::IntoResponse,
routing::{get, patch},
Json, Router,
2021-07-22 15:38:32 +02:00
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
net::SocketAddr,
sync::{Arc, RwLock},
time::Duration,
};
use tower::{BoxError, ServiceBuilder};
use tower_http::{add_extension::AddExtensionLayer, trace::TraceLayer};
use uuid::Uuid;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "example_todos=debug,tower_http=debug")
}
tracing_subscriber::fmt::init();
2021-07-22 15:38:32 +02:00
let db = Db::default();
// Compose the routes
let app = Router::new()
.route("/todos", get(todos_index).post(todos_create))
2021-07-22 15:38:32 +02:00
.route("/todos/:id", patch(todos_update).delete(todos_delete))
// Add middleware to all routes
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|error: BoxError| async move {
2021-10-24 19:33:03 +02:00
if error.is::<tower::timeout::error::Elapsed>() {
Ok(StatusCode::REQUEST_TIMEOUT)
} else {
Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
))
}
}))
2021-07-22 15:38:32 +02:00
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http())
.layer(AddExtensionLayer::new(db))
.into_inner(),
2021-10-24 19:33:03 +02:00
);
2021-07-22 15:38:32 +02:00
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
2021-07-22 15:38:32 +02:00
.serve(app.into_make_service())
.await
.unwrap();
}
// The query parameters for todos index
#[derive(Debug, Deserialize, Default)]
pub struct Pagination {
pub offset: Option<usize>,
pub limit: Option<usize>,
}
async fn todos_index(
pagination: Option<Query<Pagination>>,
Extension(db): Extension<Db>,
) -> impl IntoResponse {
let todos = db.read().unwrap();
let Query(pagination) = pagination.unwrap_or_default();
let todos = todos
.values()
.cloned()
.skip(pagination.offset.unwrap_or(0))
2021-08-18 00:04:15 +02:00
.take(pagination.limit.unwrap_or(usize::MAX))
2021-07-22 15:38:32 +02:00
.collect::<Vec<_>>();
2021-08-18 00:04:15 +02:00
Json(todos)
2021-07-22 15:38:32 +02:00
}
#[derive(Debug, Deserialize)]
struct CreateTodo {
text: String,
}
async fn todos_create(
Json(input): Json<CreateTodo>,
Extension(db): Extension<Db>,
) -> impl IntoResponse {
let todo = Todo {
id: Uuid::new_v4(),
text: input.text,
completed: false,
};
db.write().unwrap().insert(todo.id, todo.clone());
2021-08-18 00:04:15 +02:00
(StatusCode::CREATED, Json(todo))
2021-07-22 15:38:32 +02:00
}
#[derive(Debug, Deserialize)]
struct UpdateTodo {
text: Option<String>,
completed: Option<bool>,
}
async fn todos_update(
2021-08-06 16:17:57 +08:00
Path(id): Path<Uuid>,
2021-07-22 15:38:32 +02:00
Json(input): Json<UpdateTodo>,
Extension(db): Extension<Db>,
) -> Result<impl IntoResponse, StatusCode> {
let mut todo = db
.read()
.unwrap()
.get(&id)
.cloned()
.ok_or(StatusCode::NOT_FOUND)?;
if let Some(text) = input.text {
todo.text = text;
}
if let Some(completed) = input.completed {
todo.completed = completed;
}
db.write().unwrap().insert(todo.id, todo.clone());
2021-08-18 00:04:15 +02:00
Ok(Json(todo))
2021-07-22 15:38:32 +02:00
}
2021-08-06 16:17:57 +08:00
async fn todos_delete(Path(id): Path<Uuid>, Extension(db): Extension<Db>) -> impl IntoResponse {
2021-07-22 15:38:32 +02:00
if db.write().unwrap().remove(&id).is_some() {
StatusCode::NO_CONTENT
} else {
StatusCode::NOT_FOUND
}
}
type Db = Arc<RwLock<HashMap<Uuid, Todo>>>;
#[derive(Debug, Serialize, Clone)]
struct Todo {
id: Uuid,
text: String,
completed: bool,
}