-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make the generated code less complicated
- Loading branch information
1 parent
4fc11f2
commit 458501f
Showing
3 changed files
with
61 additions
and
53 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,51 @@ | ||
//! Undocumented features that are public for use in generated code (see `twirp-build`). | ||
#[doc(hidden)] | ||
pub use axum::extract::{Request, State}; | ||
use std::future::Future; | ||
|
||
#[doc(hidden)] | ||
pub use axum::routing::post; | ||
use axum::extract::{Request, State}; | ||
use axum::Router; | ||
|
||
#[doc(hidden)] | ||
pub use axum::response::Response; | ||
use crate::{server, TwirpErrorResponse}; | ||
|
||
/// Builder object used by generated code to build a router. | ||
pub struct TwirpRouterBuilder<S> { | ||
service: S, | ||
router: Router<S>, | ||
} | ||
|
||
impl<S> TwirpRouterBuilder<S> | ||
where | ||
S: Clone + Send + Sync + 'static, | ||
{ | ||
pub fn new(service: S) -> Self { | ||
TwirpRouterBuilder { | ||
service, | ||
router: Router::new(), | ||
} | ||
} | ||
|
||
pub fn route<F, G, Fut, RequestMessage, ResponseMessage>(self, url: &str, f: F) -> Self | ||
where | ||
F: Fn(S) -> G + Clone + Send + 'static, | ||
G: FnOnce(RequestMessage) -> Fut + Clone + Sync + Send + 'static, | ||
Fut: Future<Output = Result<ResponseMessage, TwirpErrorResponse>> + Send, | ||
RequestMessage: prost::Message + Default + serde::de::DeserializeOwned, | ||
ResponseMessage: prost::Message + serde::Serialize, | ||
{ | ||
TwirpRouterBuilder { | ||
service: self.service, | ||
router: self.router.route( | ||
url, | ||
axum::routing::post(move |State(api): State<S>, req: Request| async move { | ||
server::handle_request(req, f(api)).await | ||
}), | ||
), | ||
} | ||
} | ||
|
||
pub fn build(self) -> axum::Router { | ||
self.router | ||
.fallback(crate::server::not_found_handler) | ||
.with_state(self.service) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters