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

Added MongoDB example #2535

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions examples/mongodb/Cargo.toml
@@ -0,0 +1,14 @@
[package]
name = "example-mongodb"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
axum = { path = "../../axum" }
mongodb = "2.8.0"
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
tower-http = { version = "0.5.0", features = ["add-extension", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
122 changes: 122 additions & 0 deletions examples/mongodb/src/main.rs
@@ -0,0 +1,122 @@
//! Run with
//!
//! ```not_rust
//! cargo run -p example-mongodb
//! ```

use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, post, put},
Json, Router,
};
use mongodb::{bson::doc, Client, Collection};
use serde::{Deserialize, Serialize};
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[tokio::main]
async fn main() {
// connecting to mongodb
let db_connection_str = std::env::var("DATABASE_URL").unwrap_or_else(|_| {
"mongodb://admin:password@127.0.0.1:27017/?authSource=admin".to_string()
});
let client = Client::with_uri_str(db_connection_str).await.unwrap();

// pinging the database
client
.database("axum-mongo")
.run_command(doc! { "ping": 1 }, None)
.await
.unwrap();
println!("Pinged your database. Successfully connected to MongoDB!");

// logging middleware
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_mongo=debug,tower_http=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();

// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("Listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app(client)).await.unwrap();
}

// defining routes and state
fn app(client: Client) -> Router {
let collection: Collection<Member> = client.database("axum-mongo").collection("members");

Router::new()
.route("/create", post(create_member))
.route("/read/:id", get(read_member))
.route("/update", put(update_member))
.route("/delete/:id", delete(delete_member))
.layer(TraceLayer::new_for_http())
.with_state(collection)
}

// handler to create a new member
async fn create_member(
State(db): State<Collection<Member>>,
Json(input): Json<Member>,
) -> impl IntoResponse {
tr1sm0s1n marked this conversation as resolved.
Show resolved Hide resolved
let result = db.insert_one(input, None).await.unwrap();
println!("{:?}", result);
tr1sm0s1n marked this conversation as resolved.
Show resolved Hide resolved

(StatusCode::CREATED, Json(result))
}

// handler to read an existing member
async fn read_member(
State(db): State<Collection<Member>>,
Path(id): Path<u32>,
) -> impl IntoResponse {
let result = db.find_one(doc! { "_id": id }, None).await.unwrap();
println!("{:?}", result);

if result.is_none() {
return (StatusCode::NOT_FOUND, Json(result));
}

(StatusCode::OK, Json(result))
}

// handler to update an existing member
async fn update_member(
State(db): State<Collection<Member>>,
Json(input): Json<Member>,
) -> impl IntoResponse {
let result = db
.replace_one(doc! { "_id": input._id }, input, None)
.await
.unwrap();
println!("{:?}", result);

(StatusCode::OK, Json(result))
}

// handler to delete an existing member
async fn delete_member(
State(db): State<Collection<Member>>,
Path(id): Path<u32>,
) -> impl IntoResponse {
let result = db.delete_one(doc! { "_id": id }, None).await.unwrap();
println!("{:?}", result);

(StatusCode::OK, Json(result))
}

// defining Member type
#[derive(Debug, Deserialize, Serialize)]
struct Member {
_id: u32,
tr1sm0s1n marked this conversation as resolved.
Show resolved Hide resolved
name: String,
active: bool,
}