create fullstack hello world example

This commit is contained in:
Evan Almloff committed 2023-03-30 10:34:13 -05:00
1 parent 939e75541e
commit fdc8ebd1b1
11 files changed
+312 -117

No files matched your search

+42 -7
View File
@@ -4,33 +4,68 @@ use axum::{
body::{self, Body, BoxBody, Full},
http::{HeaderMap, Request, Response, StatusCode},
response::IntoResponse,
routing::post,
routing::{get, post},
Router,
};
use dioxus_core::Component;
use server_fn::{Payload, ServerFunctionRegistry};
use tokio::task::spawn_blocking;
use crate::{DioxusServerContext, DioxusServerFnRegistry, ServerFnTraitObj};
use crate::{
dioxus_ssr_html,
server_fn::{DioxusServerContext, DioxusServerFnRegistry, ServerFnTraitObj},
};
trait DioxusRouterExt {
fn register_server_fns(self) -> Self;
pub trait DioxusRouterExt {
fn register_server_fns(self, server_fn_route: &'static str) -> Self;
fn serve_dioxus_application(
self,
title: &'static str,
application_name: &'static str,
base_path: Option<&'static str>,
head: Option<&'static str>,
server_fn_route: &'static str,
app: Component,
) -> Self;
}
impl DioxusRouterExt for Router {
fn register_server_fns(self) -> Self {
fn register_server_fns(self, server_fn_route: &'static str) -> Self {
let mut router = self;
for server_fn_path in DioxusServerFnRegistry::paths_registered() {
let func = DioxusServerFnRegistry::get(server_fn_path).unwrap();
let full_route = format!("{server_fn_route}/{server_fn_path}");
router = router.route(
server_fn_path,
&full_route,
post(move |headers: HeaderMap, body: Request<Body>| async move {
server_fn_handler(DioxusServerContext {}, func.clone(), headers, body).await
// todo!()
}),
);
}
router
}
fn serve_dioxus_application(
self,
title: &'static str,
application_name: &'static str,
base_path: Option<&'static str>,
head: Option<&'static str>,
server_fn_route: &'static str,
app: Component,
) -> Self {
use tower_http::services::ServeDir;
// Serve the dist folder and the index.html file
let serve_dir = ServeDir::new("dist");
self.register_server_fns(server_fn_route)
.nest_service("/", serve_dir)
.fallback_service(get(move || {
let rendered = dioxus_ssr_html(title, application_name, base_path, head, app);
async move { Full::from(rendered) }
}))
}
}
async fn server_fn_handler(
+1 -1
View File
@@ -1,2 +1,2 @@
#[cfg(feature = "axum")]
mod axum_adapter;
pub mod axum_adapter;
+49 -99
View File
@@ -1,104 +1,54 @@
#[allow(unused)]
use dioxus_core::prelude::*;
mod adapters;
mod server_fn;
// #[server(ReadPosts, "api")]
// async fn testing(rx: i32) -> Result<u32, ServerFnError> {
// Ok(0)
// }
pub struct DioxusServerContext {}
#[cfg(any(feature = "ssr", doc))]
type ServerFnTraitObj = server_fn::ServerFnTraitObj<DioxusServerContext>;
#[cfg(any(feature = "ssr", doc))]
static REGISTERED_SERVER_FUNCTIONS: once_cell::sync::Lazy<
std::sync::Arc<
std::sync::RwLock<
std::collections::HashMap<&'static str, std::sync::Arc<ServerFnTraitObj>>,
>,
>,
> = once_cell::sync::Lazy::new(Default::default);
#[cfg(any(feature = "ssr", doc))]
/// The registry of all Dioxus server functions.
pub struct DioxusServerFnRegistry;
#[cfg(any(feature = "ssr"))]
impl server_fn::ServerFunctionRegistry<DioxusServerContext> for DioxusServerFnRegistry {
type Error = ServerRegistrationFnError;
fn register(
url: &'static str,
server_function: std::sync::Arc<ServerFnTraitObj>,
) -> Result<(), Self::Error> {
// store it in the hashmap
let mut write = REGISTERED_SERVER_FUNCTIONS
.write()
.map_err(|e| ServerRegistrationFnError::Poisoned(e.to_string()))?;
let prev = write.insert(url, server_function);
// if there was already a server function with this key,
// return Err
match prev {
Some(_) => Err(ServerRegistrationFnError::AlreadyRegistered(format!(
"There was already a server function registered at {:?}. \
This can happen if you use the same server function name \
in two different modules
on `stable` or in `release` mode.",
url
))),
None => Ok(()),
}
}
/// Returns the server function registered at the given URL, or `None` if no function is registered at that URL.
fn get(url: &str) -> Option<std::sync::Arc<ServerFnTraitObj>> {
REGISTERED_SERVER_FUNCTIONS
.read()
.ok()
.and_then(|fns| fns.get(url).cloned())
}
/// Returns a list of all registered server functions.
fn paths_registered() -> Vec<&'static str> {
REGISTERED_SERVER_FUNCTIONS
.read()
.ok()
.map(|fns| fns.keys().cloned().collect())
.unwrap_or_default()
}
pub mod prelude {
#[cfg(feature = "axum")]
pub use crate::adapters::axum_adapter::*;
pub use crate::server_fn::{DioxusServerContext, ServerFn};
pub use server_fn::{self, ServerFn as _, ServerFnError};
pub use server_macro::*;
}
#[cfg(any(feature = "ssr", doc))]
/// Errors that can occur when registering a server function.
#[derive(thiserror::Error, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum ServerRegistrationFnError {
/// The server function is already registered.
#[error("The server function {0} is already registered")]
AlreadyRegistered(String),
/// The server function registry is poisoned.
#[error("The server function registry is poisoned: {0}")]
Poisoned(String),
#[cfg(feature = "ssr")]
fn dioxus_ssr_html(
title: &str,
application_name: &str,
base_path: Option<&str>,
head: Option<&str>,
app: Component,
) -> String {
let mut vdom = VirtualDom::new(app);
let _ = vdom.rebuild();
let renderered = dioxus_ssr::pre_render(&vdom);
let base_path = base_path.unwrap_or(".");
let head = head.unwrap_or_default();
format!(
r#"
<!DOCTYPE html>
<html>
<head>
<title>{title}</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
{head}
</head>
<body>
<div id="main">
{renderered}
</div>
<script type="module">
import init from "/{base_path}/assets/dioxus/{application_name}.js";
init("/{base_path}/assets/dioxus/{application_name}_bg.wasm").then(wasm => {{
if (wasm.__wbindgen_start == undefined) {{
wasm.main();
}}
}});
</script>
</body>
</html>"#
)
}
/// Defines a "server function." A server function can be called from the server or the client,
/// but the body of its code will only be run on the server, i.e., if a crate feature `ssr` is enabled.
///
/// (This follows the same convention as the Dioxus framework's distinction between `ssr` for server-side rendering,
/// and `csr` and `hydrate` for client-side rendering and hydration, respectively.)
///
/// Server functions are created using the `server` macro.
///
/// The function should be registered by calling `ServerFn::register()`. The set of server functions
/// can be queried on the server for routing purposes by calling [server_fn_by_path].
///
/// Technically, the trait is implemented on a type that describes the server function's arguments.
pub trait ServerFn: server_fn::ServerFn<DioxusServerContext> {
/// Registers the server function, allowing the server to query it by URL.
#[cfg(any(feature = "ssr", doc))]
fn register() -> Result<(), server_fn::ServerFnError> {
Self::register_in::<DioxusServerFnRegistry>()
}
}
impl<T> ServerFn for T where T: server_fn::ServerFn<DioxusServerContext> {}
+98
View File
@@ -0,0 +1,98 @@
pub struct DioxusServerContext {}
#[cfg(any(feature = "ssr", doc))]
pub type ServerFnTraitObj = server_fn::ServerFnTraitObj<DioxusServerContext>;
#[cfg(any(feature = "ssr", doc))]
#[allow(clippy::type_complexity)]
static REGISTERED_SERVER_FUNCTIONS: once_cell::sync::Lazy<
std::sync::Arc<
std::sync::RwLock<
std::collections::HashMap<&'static str, std::sync::Arc<ServerFnTraitObj>>,
>,
>,
> = once_cell::sync::Lazy::new(Default::default);
#[cfg(any(feature = "ssr", doc))]
/// The registry of all Dioxus server functions.
pub struct DioxusServerFnRegistry;
#[cfg(any(feature = "ssr"))]
impl server_fn::ServerFunctionRegistry<DioxusServerContext> for DioxusServerFnRegistry {
type Error = ServerRegistrationFnError;
fn register(
url: &'static str,
server_function: std::sync::Arc<ServerFnTraitObj>,
) -> Result<(), Self::Error> {
// store it in the hashmap
let mut write = REGISTERED_SERVER_FUNCTIONS
.write()
.map_err(|e| ServerRegistrationFnError::Poisoned(e.to_string()))?;
let prev = write.insert(url, server_function);
// if there was already a server function with this key,
// return Err
match prev {
Some(_) => Err(ServerRegistrationFnError::AlreadyRegistered(format!(
"There was already a server function registered at {:?}. \
This can happen if you use the same server function name \
in two different modules
on `stable` or in `release` mode.",
url
))),
None => Ok(()),
}
}
/// Returns the server function registered at the given URL, or `None` if no function is registered at that URL.
fn get(url: &str) -> Option<std::sync::Arc<ServerFnTraitObj>> {
REGISTERED_SERVER_FUNCTIONS
.read()
.ok()
.and_then(|fns| fns.get(url).cloned())
}
/// Returns a list of all registered server functions.
fn paths_registered() -> Vec<&'static str> {
REGISTERED_SERVER_FUNCTIONS
.read()
.ok()
.map(|fns| fns.keys().cloned().collect())
.unwrap_or_default()
}
}
#[cfg(any(feature = "ssr", doc))]
/// Errors that can occur when registering a server function.
#[derive(thiserror::Error, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum ServerRegistrationFnError {
/// The server function is already registered.
#[error("The server function {0} is already registered")]
AlreadyRegistered(String),
/// The server function registry is poisoned.
#[error("The server function registry is poisoned: {0}")]
Poisoned(String),
}
/// Defines a "server function." A server function can be called from the server or the client,
/// but the body of its code will only be run on the server, i.e., if a crate feature `ssr` is enabled.
///
/// (This follows the same convention as the Dioxus framework's distinction between `ssr` for server-side rendering,
/// and `csr` and `hydrate` for client-side rendering and hydration, respectively.)
///
/// Server functions are created using the `server` macro.
///
/// The function should be registered by calling `ServerFn::register()`. The set of server functions
/// can be queried on the server for routing purposes by calling [server_fn_by_path].
///
/// Technically, the trait is implemented on a type that describes the server function's arguments.
pub trait ServerFn: server_fn::ServerFn<DioxusServerContext> {
/// Registers the server function, allowing the server to query it by URL.
#[cfg(any(feature = "ssr", doc))]
fn register() -> Result<(), server_fn::ServerFnError> {
Self::register_in::<DioxusServerFnRegistry>()
}
}
impl<T> ServerFn for T where T: server_fn::ServerFn<DioxusServerContext> {}