Skip to content

Commit

Permalink
refactor: ♻️ utils
Browse files Browse the repository at this point in the history
feat: ✨ config from file
  • Loading branch information
Tahinli committed Apr 4, 2024
1 parent 3ca2967 commit 1e2003f
Show file tree
Hide file tree
Showing 8 changed files with 152 additions and 75 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ debug/
target/
.vscode/
certificates/
configs/

# 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
Expand Down
14 changes: 10 additions & 4 deletions src/db/db_operations.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
use surrealdb::{engine::remote::ws::Client, Surreal};

use crate::Channel;
use crate::{Channel, DataBaseConfig};

use super::db_utils::*;

pub async fn connect() -> Option<Surreal<Client>> {
establish_connection().await
pub async fn connect(database_config: &DataBaseConfig) -> Option<Surreal<Client>> {
establish_connection(
&database_config.address,
&database_config.username,
&database_config.password,
&database_config.namespace,
&database_config.database,
)
.await
}

pub async fn create(username: &String, db: &Surreal<Client>) -> Option<Channel> {
Expand Down Expand Up @@ -93,4 +100,3 @@ pub async fn unban(victim: &String, judge: &String, db: &Surreal<Client>) -> Opt
None => None,
}
}

36 changes: 17 additions & 19 deletions src/db/db_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,27 @@ use surrealdb::{
};

use super::db_operations::{unban, unfollow};
pub async fn establish_connection() -> Option<Surreal<Client>> {
match Surreal::new::<Ws>("127.0.0.1:8000").await {
Ok(db) => {
match db
.signin(Root {
username: "root",
password: "root",
})
.await
{
Ok(_) => match db.use_ns("test").use_db("test").await {
Ok(_) => Some(db),
Err(err_val) => {
eprintln!("Error: DB Use | {}", err_val);
None
}
},
pub async fn establish_connection(
address: &String,
username: &String,
password: &String,
namespace: &String,
database: &String,
) -> Option<Surreal<Client>> {
match Surreal::new::<Ws>(address).await {
Ok(db) => match db.signin(Root { username, password }).await {
Ok(_) => match db.use_ns(namespace).use_db(database).await {
Ok(_) => Some(db),
Err(err_val) => {
eprintln!("Error: DB Login | {}", err_val);
eprintln!("Error: DB Use | {}", err_val);
None
}
},
Err(err_val) => {
eprintln!("Error: DB Login | {}", err_val);
None
}
}
},
Err(err_val) => {
eprintln!("Error: DB Connection | {}", err_val);
None
Expand Down
16 changes: 15 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
use serde::{Deserialize, Serialize};
use surrealdb::{engine::remote::ws::Client, sql::{Id, Thing}, Surreal};
use surrealdb::{
engine::remote::ws::Client,
sql::{Id, Thing},
Surreal,
};

pub mod db;
pub mod routing;
pub mod tests;
pub mod utils;

#[derive(Debug, Clone)]
pub struct DataBaseConfig {
pub address: String,
pub username: String,
pub password: String,
pub namespace: String,
pub database: String,
}

#[derive(Debug, Clone)]
pub struct AppState {
Expand Down
18 changes: 10 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use acapair_follow_ban_api::{db::db_operations::connect, routing, AppState};
use axum_server::tls_rustls::RustlsConfig;
use acapair_follow_ban_api::{
db::db_operations::connect,
routing,
utils::{database_config, tls_config},
AppState,
};
use std::{env, net::SocketAddr};

fn take_args() -> String {
Expand All @@ -14,19 +18,17 @@ fn take_args() -> String {
#[tokio::main]
async fn main() {
println!("Hello, world!");
let config =
RustlsConfig::from_pem_file("certificates/fullchain.pem", "certificates/privkey.pem")
.await
.unwrap();
let tls_config = tls_config().await;
let database_config = database_config().await;

let state = AppState {
db:connect().await.unwrap(),
db: connect(&database_config).await.unwrap(),
};

let app = routing::routing(axum::extract::State(state)).await;
let addr = SocketAddr::from(take_args().parse::<SocketAddr>().unwrap());

axum_server::bind_rustls(addr, config)
axum_server::bind_rustls(addr, tls_config)
.serve(app.into_make_service())
.await
.unwrap();
Expand Down
92 changes: 50 additions & 42 deletions src/routing.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
use axum::{extract::{Path, State}, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
};
use tower_http::cors::CorsLayer;

use crate::{db::db_operations, AppState};
use crate::{db::db_operations, utils::database_config, AppState};

pub async fn routing(State(state): State<AppState>) -> Router {
Router::new()
Expand All @@ -10,7 +16,10 @@ pub async fn routing(State(state): State<AppState>) -> Router {
.route("/delete/:username", get(delete))
.route("/search-username/:username", get(search_username))
.route("/search-id/:id", get(search_id))
.route("/change-username/:username/:updated_username", get(change_username))
.route(
"/change-username/:username/:updated_username",
get(change_username),
)
.route("/follow/:follower/:followed", get(follow))
.route("/unfollow/:follower/:followed", get(unfollow))
.route("/ban/:victim/:judge", get(ban))
Expand All @@ -20,132 +29,131 @@ pub async fn routing(State(state): State<AppState>) -> Router {
}

async fn alive() -> impl IntoResponse {
let ping = match db_operations::connect().await {
let ping = match db_operations::connect(&database_config().await).await {
Some(_) => "Alive",
None => "Dead",
};
let alive_json = serde_json::json!({
"server_status":"Alive",
"database_status":ping,
});
println!("{}", alive_json);
(StatusCode::OK, Json(alive_json))
}

async fn create(Path(username):Path<String>, State(state): State<AppState>) -> impl IntoResponse {
async fn create(Path(username): Path<String>, State(state): State<AppState>) -> impl IntoResponse {
match db_operations::create(&username, &state.db).await {
Some(channel) => {
let create = serde_json::json!({
"channel":channel,
});
(StatusCode::CREATED, Json(create))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn delete(Path(username):Path<String>, State(state): State<AppState>) -> impl IntoResponse {
async fn delete(Path(username): Path<String>, State(state): State<AppState>) -> impl IntoResponse {
match db_operations::delete(&username, &state.db).await {
Some(channel) => {
let delete = serde_json::json!({
"channel":channel,
});
(StatusCode::NO_CONTENT, Json(delete))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn search_username(Path(username):Path<String>, State(state): State<AppState>) -> impl IntoResponse {
async fn search_username(
Path(username): Path<String>,
State(state): State<AppState>,
) -> impl IntoResponse {
match db_operations::search_username(&username, &state.db).await {
Some(channel) => {
let search_username = serde_json::json!({
"channel":channel,
});
(StatusCode::OK, Json(search_username))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn search_id(Path(id):Path<String>, State(state): State<AppState>) -> impl IntoResponse {
async fn search_id(Path(id): Path<String>, State(state): State<AppState>) -> impl IntoResponse {
match db_operations::search_id(&id, &state.db).await {
Some(channel) => {
let search_id = serde_json::json!({
"channel":channel,
});
(StatusCode::OK, Json(search_id))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn change_username(Path((username, updated_username)):Path<(String, String)>, State(state): State<AppState>) -> impl IntoResponse {
async fn change_username(
Path((username, updated_username)): Path<(String, String)>,
State(state): State<AppState>,
) -> impl IntoResponse {
match db_operations::change_username(&updated_username, &username, &state.db).await {
Some(channel) => {
let change_username = serde_json::json!({
"channel":channel,
});
(StatusCode::OK, Json(change_username))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn follow(Path((follower, followed)):Path<(String, String)>, State(state): State<AppState>) -> impl IntoResponse {
async fn follow(
Path((follower, followed)): Path<(String, String)>,
State(state): State<AppState>,
) -> impl IntoResponse {
match db_operations::follow(&follower, &followed, &state.db).await {
Some(channel) => {
let follow = serde_json::json!({
"channel":channel,
});
(StatusCode::OK, Json(follow))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn unfollow(Path((follower, followed)):Path<(String, String)>, State(state): State<AppState>) -> impl IntoResponse {
async fn unfollow(
Path((follower, followed)): Path<(String, String)>,
State(state): State<AppState>,
) -> impl IntoResponse {
match db_operations::unfollow(&follower, &followed, &state.db).await {
Some(channel) => {
let unfollow = serde_json::json!({
"channel":channel,
});
(StatusCode::OK, Json(unfollow))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn ban(Path((victim, judge)):Path<(String, String)>, State(state): State<AppState>) -> impl IntoResponse {
async fn ban(
Path((victim, judge)): Path<(String, String)>,
State(state): State<AppState>,
) -> impl IntoResponse {
match db_operations::ban(&victim, &judge, &state.db).await {
Some(channel) => {
let ban = serde_json::json!({
"channel":channel,
});
(StatusCode::OK, Json(ban))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
async fn unban(Path((victim, judge)):Path<(String, String)>, State(state): State<AppState>) -> impl IntoResponse {
async fn unban(
Path((victim, judge)): Path<(String, String)>,
State(state): State<AppState>,
) -> impl IntoResponse {
match db_operations::unban(&victim, &judge, &state.db).await {
Some(channel) => {
let unban = serde_json::json!({
"channel":channel,
});
(StatusCode::OK, Json(unban))
}
None => {
(StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!("")))
}
None => (StatusCode::NOT_ACCEPTABLE, Json(serde_json::json!(""))),
}
}
}
9 changes: 8 additions & 1 deletion src/tests/db_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,14 @@ async fn create_connection_for_tests(

#[test]
async fn test_connect() {
assert_eq!(connect().await.is_some(), true);
assert_eq!(
create_connection_for_tests("test_connect")
.await
.health()
.await
.is_ok(),
true
);
}
#[test]
async fn test_create() {
Expand Down
Loading

0 comments on commit 1e2003f

Please sign in to comment.