Skip to content

Commit

Permalink
showing structures in swagger ui
Browse files Browse the repository at this point in the history
  • Loading branch information
wildonion committed Jul 14, 2024
1 parent 4841e99 commit c34dec5
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 26 deletions.
5 changes: 3 additions & 2 deletions src/apis/v1/http/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use interfaces::passport::Passport;



#[derive(Deserialize)]
#[derive(Deserialize, ToSchema)]
struct GenTokenQueries {
exp: Option<i64>,
scope: Option<String>
Expand All @@ -34,7 +34,8 @@ pub async fn generate_access_token(
});
*/
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl,
params: QueryParam<GenTokenQueries, true> // query param is required, showcasing in swagger ui
){


Expand Down
3 changes: 2 additions & 1 deletion src/apis/v1/http/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ pub async fn mint(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl,
prod: JsonBody<Product>, // used to extract the request body as well as showcasing in swagger ui
){

let app_ctx = depot.obtain::<Option<AppContext>>().unwrap(); // extracting shared app context
Expand Down
7 changes: 6 additions & 1 deletion src/apis/v1/http/hoop.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@


use models::event::EventQuery;
use salvo::Error;
use serde::{Deserialize, Serialize};
use crate::*;
Expand Down Expand Up @@ -59,8 +60,12 @@ pub async fn get_hoop(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl,
query_params: QueryParam<EventQuery, true>
){

let query_params = req.parse_queries::<EventQuery>().unwrap();

res.render("developing...")
}

Expand Down
23 changes: 15 additions & 8 deletions src/apis/v1/http/notif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,24 @@ pub async fn register_notif(
});
*/
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl,
register_notif_req: JsonBody<RegisterNotif> // used to extract the request body as well as showcasing in swagger ui
){

// if we're here means the passport verification was true and we
// can access the passed in token_string to the request header
let passport_verification_status = depot.get::<String>("passport_token_time").unwrap();

let app_ctx = depot.obtain::<Option<AppContext>>().unwrap(); // extracting shared app context
let zerlog_producer_actor = app_ctx.as_ref().unwrap().actors.clone().unwrap().broker_actors.zerlog_actor;
let app_ctx = app_ctx.clone();

// extracting the request body
let register_notif_req = req.extract::<RegisterNotif>().await.unwrap();
let get_producer_info = register_notif_req.clone().producer_info;
let get_consumer_info = register_notif_req.clone().consumer_info;

// there is a producer info in body
if get_producer_info.is_some(){
let producer_info = get_producer_info.unwrap();
let mut notif = producer_info.info;
Expand All @@ -71,7 +77,7 @@ pub async fn register_notif(
as the data coming at a same time, kindly put the sending
message logic to actor inside a loop{}.
*/
tokio::spawn( // running the producing notif job in the background in a free thread
tokio::spawn( // running the producing notif job in the background in a separate thread
{
let cloned_app_ctx = app_ctx.clone();
let cloned_notif = notif.clone();
Expand Down Expand Up @@ -100,7 +106,7 @@ pub async fn register_notif(

// in here the background task might have halted, executed or even
// crashed but the response is sent already to the caller regardless
// of what ever has happened.
// of what ever has happened inside the tokio::spawn

// fill the response object, salvo returns it by itself to the caller
res.status_code = Some(StatusCode::OK);
Expand All @@ -116,7 +122,7 @@ pub async fn register_notif(
}
));

} else if get_consumer_info.is_some(){
} else if get_consumer_info.is_some(){ // there is a consumer info in body
let consumer_info = get_consumer_info.unwrap();
let mut notif = consumer_info.info;
notif.exchange_name = format!("{}.notif:{}", APP_NAME, notif.exchange_name);
Expand All @@ -129,7 +135,7 @@ pub async fn register_notif(
you would have to send message to its actor to start it as an
async task in the background.
*/
tokio::spawn( // running the consuming notif job in the background in a free thread
tokio::spawn( // running the consuming notif job in the background in a separate thread
{
let cloned_app_ctx = app_ctx.clone();
let cloned_notif = notif.clone();
Expand Down Expand Up @@ -178,7 +184,7 @@ pub async fn register_notif(
}
));

} else{
} else{ // neither producer nor consumer are passed

// fill the response object, salvo returns it by itself to the caller
let server_time = format!("{}", chrono::Local::now().to_string());
Expand Down Expand Up @@ -210,7 +216,8 @@ pub async fn get_notif(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl,
notif_query: QueryParam<EventQuery, true> // query param is required, showcasing in swagger ui
){

let app_ctx = depot.obtain::<Option<AppContext>>().unwrap(); // extracting shared app context
Expand Down Expand Up @@ -544,7 +551,7 @@ pub async fn get_notif(

pub fn register_controller() -> Router{
Router::with_path("/v1/events/notif/")
.hoop(check_passport)
.hoop(check_passport) // before falling into each router this gets executed first
.oapi_tag("Events") // the passport verifier middleware
.post(register_notif)
.get(get_notif)
Expand Down
3 changes: 2 additions & 1 deletion src/apis/v1/ws/notif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ async fn consume(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl,
notif_query: QueryParam<EventQuery, true> // query param is required, showcasing in swagger ui
) -> Result<(), StatusError>{

let app_ctx = depot.obtain::<Option<AppContext>>().unwrap(); // extracting shared app context
Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/passport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ pub async fn check_passport(
Ok(token_time) => {

depot.insert("passport_verified", true);
depot.insert("passport_token_time", token_time);
},
Err(resp_err) => {

ctrl.skip_rest(); // skip executing all rest handlers

ctrl.skip_rest(); // skip other handlers executing cause there would be no need to execute newer handlers
depot.insert("passport_verified", false);

/* -------------------
Expand Down
10 changes: 5 additions & 5 deletions src/models/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::*;



#[derive(Serialize, Deserialize, Clone, Default, Debug)]
#[derive(Serialize, Deserialize, Clone, Default, Debug, ToSchema)]
pub struct EventQuery{
pub owner: Option<String>, // the entity owner
pub id: Option<i32>, // any entity id
Expand All @@ -19,23 +19,23 @@ pub struct EventQuery{
pub page_size: Option<u64>,
}

#[derive(Serialize, Deserialize, Clone, Default, Debug)]
#[derive(Serialize, Deserialize, Clone, Default, Debug, ToSchema)]
pub struct UpdateHoopRequest{
pub hoop_id: i32,
}

#[derive(Serialize, Deserialize, Clone, Default, Debug)]
#[derive(Serialize, Deserialize, Clone, Default, Debug, ToSchema)]
pub struct NewHoopRequest{

}

#[derive(Serialize, Deserialize, Clone, Default, Debug)]
#[derive(Serialize, Deserialize, Clone, Default, Debug, ToSchema)]
pub struct GenerateTokenTimeQuery{
pub exp_time: Option<u64>, // in seconds
pub scope: Option<String>
}

#[derive(Serialize, Deserialize, Clone, Default, Debug)]
#[derive(Serialize, Deserialize, Clone, Default, Debug, ToSchema)]
pub enum TokenTimeScope{
#[default]
Write,
Expand Down
52 changes: 46 additions & 6 deletions src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use crate::*;
use actix::{Actor, Addr, AsyncContext, Context};
use actix_web::middleware::Compress;
use constants::{NEXT_USER_ID, ONLINE_USERS, WS_ROOMS};
use futures::{lock, FutureExt};
use models::event::EventQuery;
Expand All @@ -24,7 +25,7 @@ pub trait HoopoeService<G: Send + Sync>{ // supports polymorphism
pub struct HoopoeServer{
pub service: Option<Service>,
pub addr: String,
pub app_ctx: Option<AppContext>,
pub app_ctx: Option<AppContext>, // the whole app context: db, actors and global types
pub ssl_domain: Option<String>
}

Expand All @@ -38,15 +39,35 @@ impl HoopoeServer{
let app_ctx = self.app_ctx.clone();
let router = Router::new()
.push(routers::register_app_controllers())
.hoop(Compression::new().enable_brotli(CompressionLevel::Fastest))
.hoop(Logger::new()) // register middlewares using hoop() method
.hoop(affix::inject(app_ctx))
.hoop(cors);

// adding swagger ui route
// adding api ui routes
let doc = OpenApi::new("Hoopoe Api", "0.1.0").merge_router(&router);
let router = router
.push(doc.into_router("/api-doc/openapi.json"))
.push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger"));
.unshift(
Scalar::new("/api-doc/openapi.json")
.title("Hoopoe - Scalar")
.into_router("scalar"),
)
.unshift(
SwaggerUi::new("/api-doc/openapi.json")
.title("Hoopoe - Swagger UI")
.into_router("swagger")
)
.unshift(
RapiDoc::new("/api-doc/openapi.json")
.title("Hoopoe - RapiDoc")
.into_router("rapidoc"),
)
.unshift(
ReDoc::new("/api-doc/openapi.json")
.title("Hoopoe - ReDoc")
.into_router("redoc"),
);
router
}

Expand All @@ -57,16 +78,35 @@ impl HoopoeServer{
.into_handler();
let router = Router::new()
.push(routers::register_app_controllers())
.hoop(Compression::new().enable_brotli(CompressionLevel::Fastest))
.hoop(Logger::new()) // register middlewares using hoop() method
.hoop(affix::inject(app_ctx))
.hoop(cors);


// adding swagger ui route
let doc = OpenApi::new("Hoopoe Api", "0.1.0").merge_router(&router);
let router = router
.push(doc.into_router("/api-doc/openapi.json"))
.push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger"));
.unshift(
Scalar::new("/api-doc/openapi.json")
.title("Hoopoe - Scalar")
.into_router("scalar"),
)
.unshift(
SwaggerUi::new("/api-doc/openapi.json")
.title("Hoopoe - Swagger UI")
.into_router("swagger")
)
.unshift(
RapiDoc::new("/api-doc/openapi.json")
.title("Hoopoe - RapiDoc")
.into_router("rapidoc"),
)
.unshift(
ReDoc::new("/api-doc/openapi.json")
.title("Hoopoe - ReDoc")
.into_router("redoc"),
);
router
}

Expand Down Expand Up @@ -440,7 +480,7 @@ impl HoopoeWsServerActor{
})
.or_insert(users); // if the key is not there insert a new user ids
});


while let Some(result) = current_user_ws_rx.next().await {
let msg = match result {
Expand Down

0 comments on commit c34dec5

Please sign in to comment.