Skip to content

Commit

Permalink
馃殌 first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
flaviodelgrosso committed Jan 14, 2024
0 parents commit dfec9ab
Show file tree
Hide file tree
Showing 33 changed files with 1,116 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
CARGO_ENV=development
RUST_LOG=debug

APP_HOST=127.0.0.1
APP_PORT=5000

MONGO_URI=mongodb://localhost:27017
MONGO_DB=rust-axum-boilerplate-db

ACCESS_TOKEN_SECRET=ddd26ab8c5140fb0dc5bd8cdccd6a0102d09c9bdf2466a5cd718373fd42a17b1
REFRESH_TOKEN_SECRET=bdca01f8df0bfba0e400f3daf3e629118b76fe8b15d7362bbabb57496a30bdfc
ARGON_SALT=4a936421ec2c38de8e968c0e80959aae8158df7fe541d774c173e0a8b3390545
21 changes: 21 additions & 0 deletions .github/workflows/releases.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Release

permissions:
contents: write

on:
push:
tags:
- v[0-9]+.*

jobs:
create-release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: taiki-e/create-gh-release-action@v1
with:
# (optional) Path to changelog.
# changelog: CHANGELOG.md
# (required) GitHub token for creating GitHub Releases.
token: ${{ secrets.GITHUB_TOKEN }}
48 changes: 48 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

# Generated by Cargo
# will have compiled files and executables
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb

logs/*
!logs/.gitkeep

# docker volumes
data
.data
69 changes: 69 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in library 'database'",
"cargo": {
"args": ["test", "--no-run", "--lib", "--package=database"],
"filter": {
"name": "database",
"kind": "lib"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in library 'utils'",
"cargo": {
"args": ["test", "--no-run", "--lib", "--package=utils"],
"filter": {
"name": "utils",
"kind": "lib"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug executable 'rust-axum-boilerplate'",
"cargo": {
"args": ["build", "--bin=rust-axum-boilerplate", "--package=server"],
"filter": {
"name": "rust-axum-boilerplate",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in executable 'rust-axum-boilerplate'",
"cargo": {
"args": [
"test",
"--no-run",
"--bin=rust-axum-boilerplate",
"--package=server"
],
"filter": {
"name": "rust-axum-boilerplate",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}
]
}
27 changes: 27 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[workspace]
members = ["crates/*"]
resolver = "2"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[workspace.dependencies]
anyhow = "1.0.79"
async-trait = "0.1.77"
axum = { version = "0.7.3", features = ["macros"] }
clap = { version = "4.4.13", features = ["env", "derive"] }
dotenvy = "0.15.7"
lazy_static = "1.4.0"
mongodb = { version = "2.8.0" }
pbkdf2 = "0.12.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.68"
time = "0.3.31"
thiserror = "1.0.56"
tokio = { version = "1", features = ["full"] }
tokio-stream = { version = "0.1.14" }
tower = { version = "0.4.13", features = ["timeout", "buffer", "limit"] }
tower-http = { version = "0.5.0", features = ["fs", "trace", "cors"] }
tracing = { version = "0.1.40" }
tracing-appender = "0.2.3"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
validator = { version = "0.16.1", features = ["derive"] }
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Flavio Del Grosso

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Rust Application Server Boilerplate using Axum framework and MongoDB! 馃

This project is a boilerplate for building a Rust application server using the [Axum framework]("https://github.com/tokio-rs/axum") and MongoDB as the database. It provides a solid starting point for building your own Rust applications, with many common features already implemented.

## Features

- [x] Axum server: A modern and fast web framework with a focus on ergonomics and modularity.
- [x] MongoDB driver: A Rust driver for MongoDB, allowing you to interact with MongoDB collections.
- [x] Logging: Logging support using `tracing` and `tracing-subscriber` for async-compatible logging.
- [x] Error handler: Application error handling system.
- [x] Router: A router for mapping requests to handlers, cors, and static files.
- [x] Static: Static file serving using `tower-http`.
- [x] Extractors: Validation extractor for getting data from requests and validate with `validator` crate.
- [x] App config (dotenvy): Load your application's configuration from a `.env` file.

## Possible Planned Features

- Authentication: User authentication system.
- Hashing: Password hashing
- Jwt utils: Utilities for working with JWTs.
- Server Metrics

## Project Structure

The project is organized into several crates:

- `database`: Contains the MongoDB driver and user model and repository.
- `server`: Contains the main application server, including the API, router, and services.
- `utils`: Contains utility modules like config and errors.

## Getting Started

1. Clone the repository.
2. Install the Rust toolchain if you haven't already.
3. Run `cargo build` to build the project.
4. Run `cargo run` to start the server.

You can install cargo-watch to automatically recompile the project when changes are made:

```bash
cargo install cargo-watch
```

Then run `cargo watch -x run` to start the server.

## Contributing

Contributions are welcome!

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
18 changes: 18 additions & 0 deletions crates/database/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "database"
version = "0.1.0"
edition = "2021"
metadata.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-trait = { workspace = true }
mongodb = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
time = { workspace = true }
tokio-stream = { workspace = true }
tracing = { workspace = true }
utils = { path = "../utils" }
validator = { workspace = true }
26 changes: 26 additions & 0 deletions crates/database/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
pub mod user;

use std::sync::Arc;

use mongodb::{Client, Collection};
use tracing::info;

use user::model::User;
use utils::{AppConfig, AppResult};

#[derive(Clone, Debug)]
pub struct Database {
pub user_col: Collection<User>,
}

impl Database {
pub async fn new(config: Arc<AppConfig>) -> AppResult<Self> {
let client = Client::with_uri_str(&config.mongo_uri).await?;
let db = client.database(&config.mongo_db);
let user_col: Collection<User> = db.collection("User");

info!("initializing database connection...");

Ok(Database { user_col })
}
}
2 changes: 2 additions & 0 deletions crates/database/src/user/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod model;
pub mod repository;
15 changes: 15 additions & 0 deletions crates/database/src/user/model.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use mongodb::bson::oid::ObjectId;
use serde::{Deserialize, Serialize};
use validator::Validate;

#[derive(Debug, Clone, Serialize, Deserialize, Validate, Default)]
pub struct User {
#[serde(rename = "_id", skip_deserializing, skip_serializing)]
pub id: Option<ObjectId>,
#[validate(length(min = 1))]
pub name: String,
#[validate(length(min = 1), email(message = "email is invalid"))]
pub email: String,
#[validate(length(min = 6))]
pub password: String,
}
Loading

0 comments on commit dfec9ab

Please sign in to comment.