feat: create server side api handler

This commit is contained in:
Valerio Ageno
2024-05-20 21:07:37 +02:00
parent 04216d93bf
commit 9a0bb45a03
2 changed files with 19 additions and 6 deletions
+4 -2
View File
@@ -25,7 +25,6 @@ async fn main() {
let app = Router::new()
// ROUTE_BUILDER
.nest_service("/__tuono", ServeDir::new(".tuono"))
.fallback_service(ServeDir::new("public").fallback(get(catch_all)));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
@@ -119,7 +118,10 @@ fn create_axum_routes_declaration(routes: &HashMap<String, String>) -> String {
let mut route_declarations = String::from("// ROUTE_BUILDER\n");
for (route, _path) in routes.iter() {
route_declarations.push_str(&format!(r#".route("/{route}", get({route}::route))"#))
route_declarations.push_str(&format!(r#".route("/{route}", get({route}::route))"#));
route_declarations.push_str(&format!(
r#".route("/__tuono/data/{route}", get({route}::api))"#
));
}
route_declarations
+15 -4
View File
@@ -8,12 +8,11 @@ pub fn handler_core(_args: TokenStream, item: TokenStream) -> TokenStream {
let fn_name = item.clone().sig.ident;
quote! {
use axum::response::Html;
use axum::response::{Html, IntoResponse};
#item
pub async fn route(request: axum::extract::Request) -> Html<String> {
println!("Custom handler");
let pathname = &request.uri();
let headers = &request.headers();
@@ -35,12 +34,24 @@ pub fn handler_core(_args: TokenStream, item: TokenStream) -> TokenStream {
_ => Ok("500 Internal server error".to_string())
};
match res {
Ok(html) => Html(html),
_ => Html("500 internal server error".to_string())
}
}
pub async fn api(request: axum::extract::Request) -> axum::response::Response {
let pathname = &request.uri();
let headers = &request.headers();
let req = tuono_lib::Request::new(pathname, headers);
let local_response = #fn_name(&req);
let res = match local_response{
tuono_lib::Response::Props(val) => return axum::Json(val).into_response(),
_ => return axum::Json("").into_response()
};
}
}
.into()