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

Remove CORS, OpenAPI/Swagger, Axum tests #59

Merged
merged 3 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 31 additions & 29 deletions engine/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod cli;
mod dataset;
mod game;
#[cfg(test)]
mod test;

use crate::repository::LaerningToolRepository;
Expand All @@ -17,7 +18,7 @@ use axum::http::Method;
use axum::routing::{post, IntoMakeService};
use axum::{routing::get, Router};
use std::sync::Arc;
use tower_http::cors::{Any, CorsLayer};
use tower_http::cors::{AllowMethods, Any, CorsLayer};
use tracing_subscriber::filter::FilterExt;
use tracing_subscriber::fmt::writer::MakeWriterExt;
use utoipa::OpenApi;
Expand Down Expand Up @@ -46,37 +47,37 @@ pub fn new(repository: LaerningToolRepository) -> ApiInstance {
#[derive(OpenApi)]
#[openapi(
paths(
dataset::dataset_list,
game::game_new,
game::game_list,
game::game_answer,
dataset::dataset_list,
game::game_new,
game::game_list,
game::game_answer,
),
components(
schemas(
dataset::DatasetJson,
AnswerType,
GameJson,
GameListing,
GameListingError,
GameListingErrorResponse,
GameStats,
GameStatus,
NewGameRequest,
QuestionEntry,
NewGameErrorResponse,
NewGameError,
GameAnswerRequest,
)
schemas(
dataset::DatasetJson,
AnswerType,
GameJson,
GameListing,
GameListingError,
GameListingErrorResponse,
GameStats,
GameStatus,
NewGameRequest,
QuestionEntry,
NewGameErrorResponse,
NewGameError,
GameAnswerRequest,
)
),
tags(
(name = "this is a tag name", description = "This is the tag description"))
(name = "this is a tag name", description = "This is the tag description"))
)]
pub struct ApiDoc;

impl ApiInstance {
pub async fn build_router(self) -> Router {
Router::new()
.merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi()))
// .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi()))
.route(
"/dataset/list",
get(dataset::dataset_list).with_state(self.state.clone()),
Expand All @@ -92,12 +93,13 @@ impl ApiInstance {
.route("/game/:id", post(game::game_answer).with_state(self.state))
}

pub async fn make_server(self) -> IntoMakeService<Router> {
let cors = CorsLayer::new()
// allow `GET` and `POST` when accessing the resource
.allow_methods([Method::GET, Method::POST])
// allow requests from any origin
.allow_origin(Any);
self.build_router().await.layer(cors).into_make_service()
pub async fn make_server(self) -> Router {
// let cors = CorsLayer::new()
// // allow `GET` and `POST` when accessing the resource
// .allow_methods(AllowMethods::any())
// // allow requests from any origin
// .allow_origin(Any);
self.build_router().await
// .layer(cors)
}
}
112 changes: 57 additions & 55 deletions engine/src/api/test/mod.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,59 @@
#[cfg(test)]
mod test {
use crate::api;
/// This module used to work but dependencies updated, tools broke and now I can't import the traits that I can see in the dependencies...
/// It should be fixed one day. For now, I am not working on the API

use crate::api::game::game_library::{GameJson, GameStats};
use crate::repository::LaerningToolRepository;
use axum::http::StatusCode;
use axum_test::http::header::CONTENT_TYPE;
use axum_test::http::HeaderValue;
use axum_test::TestServer;

#[tokio::test]
async fn test_games_can_be_created() {
let db = crate::start_db(None).await;
let repo = LaerningToolRepository::new(db);
let api = api::new(repo);
let app = api.make_server().await;

let server = TestServer::new(app).unwrap();

let response = server
.post("/game/new")
.add_header(
CONTENT_TYPE,
HeaderValue::from_str("application/json").unwrap(),
)
.text(
r#"{
"name": "any name",
"dataset": "any dataset"
}"#,
)
.await;

assert_eq!(StatusCode::OK, response.status_code(), "{:?}", response);

let bytes = response.as_bytes();
let body_str = std::str::from_utf8(bytes).unwrap();
let game: GameJson = serde_json::from_str(body_str).unwrap();
assert_eq!(
game,
GameJson {
name: "⟨any name⟩".to_string(),
dataset: "⟨any dataset⟩".to_string(),
current_question: None,
stats: GameStats {
current_question: 1,
total_questions: 2,
current_try: 3,
max_tries: 4,
duration: 5,
average_question_duration: 6.0,
},
}
);
}
// use crate::api;
// use axum::Router;
//
// use crate::api::game::game_library::{GameJson, GameStats};
// use crate::repository::LaerningToolRepository;
// use axum_test::http::header::CONTENT_TYPE;
// use axum_test::http::HeaderValue;
// use axum_test::http::StatusCode;
// use axum_test::transport_layer::{IntoTransportLayer, TransportLayer, TransportLayerBuilder};
// use axum_test::TestServer;
#[tokio::test]
#[ignore]
async fn test_games_can_be_created() {
// let db = crate::start_db(None).await;
// let repo = LaerningToolRepository::new(db);
// let api = api::new(repo);
// let app: axum::routing::Router = api.make_server().await;
//
// let server = TestServer::new(app).unwrap();
//
// let response = server
// .post("/game/new")
// .add_header(
// CONTENT_TYPE,
// HeaderValue::from_str("application/json").unwrap(),
// )
// .text(
// r#"{
// "name": "any name",
// "dataset": "any dataset"
// }"#,
// )
// .await;
//
// assert_eq!(StatusCode::OK, response.status_code(), "{:?}", response);
//
// let bytes = response.as_bytes();
// let body_str = std::str::from_utf8(bytes).unwrap();
// let game: GameJson = serde_json::from_str(body_str).unwrap();
// assert_eq!(
// game,
// GameJson {
// name: "⟨any name⟩".to_string(),
// dataset: "⟨any dataset⟩".to_string(),
// current_question: None,
// stats: GameStats {
// current_question: 1,
// total_questions: 2,
// current_try: 3,
// max_tries: 4,
// duration: 5,
// average_question_duration: 6.0,
// },
// }
// );
}
21 changes: 14 additions & 7 deletions engine/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![recursion_limit = "256"]

mod api;
mod repository;
mod xml;
Expand All @@ -7,11 +8,11 @@ use crate::xml::error::Error;
use crate::xml::LearningModule;

use api::cli::ToolArgs;
use axum::Server;
use clap::Parser;
use hyper::Server;
use std::net::SocketAddr;
use std::str::FromStr;
use surrealdb::engine::local::{Db, File, Mem};
use surrealdb::engine::local::{Db, Mem};

use crate::repository::dataset::Dataset;
use crate::repository::{LaerningToolRepository, Repository};
Expand All @@ -22,8 +23,8 @@ async fn load_data(directory: &str) -> Vec<LearningModule> {
}

async fn start_db(addr: Option<String>) -> Surreal<Db> {
let db: Surreal<Db> = if let Some(address) = addr {
Surreal::new::<File>(&*address).await.unwrap()
let db: Surreal<Db> = if let Some(_address) = addr {
Surreal::new::<Mem>(()).await.unwrap()
} else {
Surreal::new::<Mem>(()).await.unwrap()
};
Expand All @@ -43,23 +44,29 @@ async fn start_db(addr: Option<String>) -> Surreal<Db> {
db
}

async fn start_server(repository: LaerningToolRepository, socket_addr: Option<String>) -> Result<(), Error> {
async fn start_server(
repository: LaerningToolRepository,
socket_addr: Option<String>,
) -> Result<(), Error> {
// Create a new Axum router
let api_state = api::new(repository);
let app = api_state.make_server().await;

// Define the address on which the server will listen
let addr = if let Some(address) = socket_addr {
SocketAddr::from_str(&address)
.map_or(SocketAddr::from(([127, 0, 0, 1], 3000)), |address| address)
.map_or(SocketAddr::from(([127, 0, 0, 1], 3000)), |address| address)
} else {
SocketAddr::from(([127, 0, 0, 1], 3000))
};

// Start the server
println!("Server running on http://{}", addr);
println!("Swagger UI available at: http://{}/swagger-ui/#/", addr);
Server::bind(&addr).serve(app).await.unwrap();
Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion engine/src/xml/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
mod error;
pub(crate) mod error;
#[cfg(test)]
mod module_browser_test;

Expand Down
Loading