Skip to content

Commit

Permalink
refactor(server): ♻️ setup simple graphql endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
keinsell committed Jun 13, 2024
1 parent bb6dfb4 commit d289daa
Show file tree
Hide file tree
Showing 28 changed files with 1,581 additions and 696 deletions.
434 changes: 235 additions & 199 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions apps/rust-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ rocket = { version = "^0.5.0-rc.2", features = [
"mtls",
"uuid",
] }
seaography = "1.0.0-rc.4"
ndb = { path = "./../../db/rust-seaorm-client", package = "neuronek-database-client" }
sea-orm = { version = "0.12", features = [
sea-orm = { version = "1.0.0-rc.4", features = [
"sqlx-sqlite",
"runtime-async-std-native-tls",
"macros",
Expand All @@ -44,7 +45,6 @@ sea-orm = { version = "0.12", features = [
"with-rust_decimal",
"with-bigdecimal",
] }
sea-orm-migration = "^0.12.0"
utoipa = { version = "4", features = ["rocket_extras", "chrono", "debug"] }
utoipa-scalar = { version = "*", features = ["rocket"] }
async-graphql = { version = "7.0.6", features = [
Expand Down
117 changes: 69 additions & 48 deletions apps/rust-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@ use async_graphql::{
use async_graphql_rocket::*;
use async_std::task_local;
use graphql_schema::*;
use ndb::Migrator;
use ndb::{IntoSchemaManagerConnection, Migrator, MigratorTrait};
use orm::setup_database;
use response::content;
use rocket::*;
use sea_orm::{DatabaseConnection, *};
use sea_orm_migration::*;
use utoipa::{
openapi::security::{ApiKey, ApiKeyValue, SecurityScheme},
Modify, OpenApi, ToSchema,
Expand All @@ -43,68 +42,54 @@ fn graphql_playground() -> content::RawHtml<String> {
content::RawHtml(playground_source(GraphQLPlaygroundConfig::new("/graphql")))
}

#[derive(OpenApi)]
#[openapi(
paths(
substance_api::list_substances
),
components(
schemas(
substance_api::Substance,
)
),
tags(
(name = "substance", description = "Substance-related operations.")
),
modifiers(&SecurityAddon)
)]
struct ApiDoc;

struct SecurityAddon;

impl Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {}
}

#[launch]
async fn rocket() -> _ {
#[derive(OpenApi)]
#[openapi(
paths(
substance_api::list_substances
),
components(
schemas(
substance_api::Substance,
)
),
tags(
(name = "substance", description = "Substance-related operations.")
),
modifiers(&SecurityAddon)
)]
struct ApiDoc;

struct SecurityAddon;

impl Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
// let components = openapi.components.as_mut().unwrap();
// components.add_security_scheme(
// "api_key",
// SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::new("
// todo_apikey"))), )
}
}

let db = match setup_database().await {
Ok(db) => db,
Err(err) => panic!("{}", err),
};

match Migrator::up(db.into_schema_manager_connection(), None).await {
Ok(_) => debug!("Migrations applied"),
Err(error) => panic!("Could not migrate database schema: {}", error),
};

let db = match setup_database().await {
Ok(db) => db,
Err(err) => panic!("{}", err),
};

let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.data(db)
.data(db.clone())
.finish();

let db = match setup_database().await {
Ok(db) => db,
Err(err) => panic!("{}", err),
};
println!("{:?}", schema.sdl().clone());

rocket::build()
.manage(db)
.manage(schema)
.mount("/", Scalar::with_url("/", ApiDoc::openapi()))
// Setup GraphQL
.mount("/graphql", routes![graphql_request, graphql_playground])
.mount("/", routes![substance_api::list_substances])
.mount(
"/",
routes![
substance_api::list_substances,
substance_api::get_substance_by_id
],
)
}

mod substance_api {
Expand Down Expand Up @@ -174,4 +159,40 @@ mod substance_api {

Json(substances)
}

#[utoipa::path(
path = "/substance/{id}",
responses(
(status = 200, description = "Substances retrieved successfully", body = Substance),
(status = 500, description = "Internal server error"),
),
security()
)]
#[get("/substance/<id>")]
pub(super) async fn get_substance_by_id(
db: &State<DatabaseConnection>,
id: String,
) -> Json<Substance> {
let database_connection = db as &DatabaseConnection;
let substance: ndb::substance::Model = ndb::substance::Entity::find_by_id(id)
.one(database_connection)
.await
.unwrap()
.unwrap();

Json(Substance {
id: substance.id.to_string(),
})
}
}

mod account {}
mod authentication {}
mod ingestion {}
mod route_of_administration {}
mod dosage {}
mod phase {}
mod substance {}
mod subject {}
mod experience {}
mod search {}
11 changes: 11 additions & 0 deletions apps/rust-server/src/orm.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// src/setup.rs

use ndb::{IntoSchemaManagerConnection, Migrator, MigratorTrait};
use sea_orm::*;

const DATABASE_URL: &str = "sqlite::memory:";
Expand All @@ -16,5 +17,15 @@ pub(super) async fn setup_database() -> Result<DatabaseConnection, DbErr> {
DbBackend::Sqlite => db,
};

match Migrator::refresh(db.into_schema_manager_connection()).await {
Ok(_) => {
println!("Database schema updated");
}
Err(error) => {
println!("Error while updating database schema: {}", error);
panic!("Could not migrate database schema: {}", error)
}
};

Ok(db)
}
51 changes: 51 additions & 0 deletions apps/rust-server/src/pool.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use std::time::Duration;

use async_trait::async_trait;
use sea_orm::ConnectOptions;
use sea_orm_rocket::{rocket::figment::Figment, Config, Database};

#[derive(Database, Debug)]
#[database("sea_orm")]
pub struct Db(SeaOrmPool);

#[derive(Debug, Clone)]
pub struct SeaOrmPool {
pub conn: sea_orm::DatabaseConnection,
}

#[async_trait]
impl sea_orm_rocket::Pool for SeaOrmPool {
type Error = sea_orm::DbErr;

type Connection = sea_orm::DatabaseConnection;

async fn init(figment: &Figment) -> Result<Self, Self::Error> {
let db = match setup_database().await {
Ok(db) => db,
Err(err) => panic!("{}", err),
};

match Migrator::up(db.into_schema_manager_connection(), None).await {
Ok(_) => debug!("Migrations applied"),
Err(error) => panic!("Could not migrate database schema: {}", error),
};

let config = figment.extract::<Config>().unwrap();
let mut options: ConnectOptions = config.url.into();
options
.max_connections(config.max_connections as u32)
.min_connections(config.min_connections.unwrap_or_default())
.connect_timeout(Duration::from_secs(config.connect_timeout))
.sqlx_logging(config.sqlx_logging);
if let Some(idle_timeout) = config.idle_timeout {
options.idle_timeout(Duration::from_secs(idle_timeout));
}
let conn = sea_orm::Database::connect(options).await?;

Ok(SeaOrmPool { conn })
}

fn borrow(&self) -> &Self::Connection {
&self.conn
}
}
Loading

0 comments on commit d289daa

Please sign in to comment.