Skip to content

Commit

Permalink
test: ✅ search_id, search_id_non
Browse files Browse the repository at this point in the history
feat: ✨ routing
feat: ✨ search id
  • Loading branch information
Tahinli committed Apr 4, 2024
1 parent 66cc09a commit 2ebb0b1
Show file tree
Hide file tree
Showing 9 changed files with 296 additions and 77 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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
axum = "0.7.5"
axum = { version = "0.7.5", features = ["macros"] }
axum-server = { version = "0.6.0", features = ["tls-rustls"] }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
Expand Down
33 changes: 15 additions & 18 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 All @@ -15,13 +22,15 @@ pub async fn create(username: &String, db: &Surreal<Client>) -> Option<Channel>
}
}

pub async fn search(username: &String, db: &Surreal<Client>) -> Option<Channel> {
pub async fn search_username(username: &String, db: &Surreal<Client>) -> Option<Channel> {
search_channel_by_username(username, db).await
}

pub async fn search_id(id: &String, db: &Surreal<Client>) -> Option<Channel> {
search_channel_by_id(&id.into(), db).await
}

pub async fn delete(username: &String, db: &Surreal<Client>) -> Option<Channel> {
// delete channel should be last for mind sake
// first artifacts
match search_channel_by_username(username, db).await {
Some(channel) => match remove_all_followers(channel.clone(), db).await {
Some(_) => match remove_all_followed(channel.clone(), db).await {
Expand All @@ -41,18 +50,6 @@ pub async fn delete(username: &String, db: &Surreal<Client>) -> Option<Channel>
None
}
}
// match delete_channel(username, db).await {
// Some(deleted_channel) => {
// match remove_follower_artifacts(deleted_channel.clone(), db).await {
// Some(_) => match remove_banned_artifacts(deleted_channel.clone(), db).await {
// Some(_) => Some(deleted_channel),
// None => None,
// },
// None => None,
// }
// }
// None => None,
// }
}

pub async fn change_username(
Expand Down
38 changes: 18 additions & 20 deletions src/db/db_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,35 @@ 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
}
}
}

async fn search_channel_by_id(id: &Id, db: &Surreal<Client>) -> Option<Channel> {
pub async fn search_channel_by_id(id: &Id, db: &Surreal<Client>) -> Option<Channel> {
let searced: Option<Channel> = db.select(("channel", id.clone())).await.unwrap();
searced
}
Expand Down
20 changes: 18 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
use serde::{Deserialize, Serialize};
use surrealdb::sql::{Id, Thing};
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 AppState {}
pub struct DataBaseConfig {
pub address: String,
pub username: String,
pub password: String,
pub namespace: String,
pub database: String,
}

#[derive(Debug, Clone)]
pub struct AppState {
pub db: Surreal<Client>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Channel {
Expand Down
22 changes: 14 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::{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,17 +18,19 @@ 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 {};
println!("{:#?}", database_config);

let state = AppState {
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
143 changes: 139 additions & 4 deletions src/routing.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,159 @@
use axum::{extract::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()
.route("/", get(alive))
.route("/create/:username", get(create))
.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("/follow/:follower/:followed", get(follow))
.route("/unfollow/:follower/:followed", get(unfollow))
.route("/ban/:victim/:judge", get(ban))
.route("/unban/:victim/:judge", get(unban))
.layer(CorsLayer::permissive())
.with_state(state.clone())
}

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 {
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!(""))),
}
}
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!(""))),
}
}
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!(""))),
}
}
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!(""))),
}
}
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!(""))),
}
}
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!(""))),
}
}
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!(""))),
}
}
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!(""))),
}
}
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!(""))),
}
}
Loading

0 comments on commit 2ebb0b1

Please sign in to comment.