CF worker example

This commit is contained in:
Greg Johnston
2022-12-14 07:49:06 -05:00
parent 896812c8d6
commit d40c48ab9b
8 changed files with 199 additions and 0 deletions

View File

@@ -18,6 +18,7 @@ members = [
"router",
# examples
"examples/cloudflare-worker",
"examples/counter",
"examples/counter-isomorphic",
"examples/counters",

View File

@@ -0,0 +1,13 @@
# http://editorconfig.org
root = true
[*]
indent_style = tab
tab_width = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_style = space

10
examples/cloudflare-worker/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
.DS_Store
/node_modules
**/*.rs.bk
wasm-pack.log
build/
/target
/dist
pkg

View File

@@ -0,0 +1,20 @@
[package]
name = "counter-worker"
version = "0.0.0"
edition = "2018"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
cfg-if = "1"
worker = { version = "0.0.12", optional = true }
serde_json = "1"
leptos = { path = "../../leptos", default-features = false }
console_error_panic_hook = "0.1"
wasm-bindgen = "0.2"
[features]
default = ["ssr"]
ssr = ["leptos/ssr", "dep:worker"]
hydrate = ["leptos/hydrate"]

View File

@@ -0,0 +1,19 @@
This example shows the basics of how youd render a Leptos component to HTML in a Cloudflare Worker and then hydrate it on the client side.
First, compile the client-side WebAssembly with
```sh
wasm-pack build --target=web --no-default-features --features=hydrate
```
Then run the Worker:
```sh
# run your Worker in an ideal development workflow (with a local server, file watcher & more)
$ npm run dev
# deploy your Worker globally to the Cloudflare network (update your wrangler.toml file for configuration)
$ npm run deploy
```
## Important Note
It's possible the URL for some of the JS necessary for hydration will change between `wasm-pack` builds. Obviously this is not great, but this is a proof of concept more than anything. If there's trouble loading JS, check the URL at `lib.rs:72` against the filenames in `pkg` and adjust `lib.rs` to match the correct path.

View File

@@ -0,0 +1,11 @@
{
"private": true,
"version": "0.0.0",
"scripts": {
"deploy": "wrangler publish",
"dev": "wrangler dev --local"
},
"devDependencies": {
"wrangler": "^2.0.0"
}
}

View File

@@ -0,0 +1,116 @@
use cfg_if::cfg_if;
use leptos::*;
use worker::ResponseBody;
const PKG_PATH: &str = "/pkg/counter_worker";
#[component]
pub fn Counter(cx: Scope) -> Element {
let (value, set_value) = create_signal(cx, 0);
view! { cx,
<div>
<button on:click=move |_| set_value(0)>"Clear"</button>
<button on:click=move |_| set_value.update(|value| *value -= 1)>"-1"</button>
<span>"Value: " {move || value().to_string()} "!"</span>
<button on:click=move |_| set_value.update(|value| *value += 1)>"+1"</button>
</div>
}
}
// Load client-side Wasm and hydrate rendered app
cfg_if! {
if #[cfg(feature = "hydrate")] {
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
leptos::hydrate(body().unwrap(), move |cx| {
view! { cx, <Counter/> }
});
}
} else {
use worker::*;
use serde_json::json;
fn log_request(req: &Request) {
console_log!(
"{} - [{}], located at: {:?}, within: {}",
Date::now().to_string(),
req.path(),
req.cf().coordinates().unwrap_or_default(),
req.cf().region().unwrap_or_else(|| "unknown region".into())
);
}
#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
log_request(&req);
// Optionally, use the Router to handle matching endpoints, use ":name" placeholders, or "*name"
// catch-alls to match on specific patterns. Alternatively, use `Router::with_data(D)` to
// provide arbitrary data that will be accessible in each route via the `ctx.data()` method.
let router = Router::new();
// Add as many routes as your Worker needs! Each route will get a `Request` for handling HTTP
// functionality and a `RouteContext` which you can use to and get route parameters and
// Environment bindings like KV Stores, Durable Objects, Secrets, and Variables.
router
.get("/", |_, _| Response::from_html(render_html_page(&render_to_string(|cx| view! { cx, <Counter/> }))))
// serve JS to load Wasm
// this section is kind of a mess; ideally it could point to static files rather than inlining them and serving like this
.get(&format!("{PKG_PATH}.js"), |_, _| {
let mut headers = Headers::new();
headers.set("Content-Type", "text/javascript")?;
let body = ResponseBody::Body(include_str!("../pkg/counter_worker.js").as_bytes().to_vec());
Ok(
Response::from_body(body)?
.with_headers(headers)
)
})
.get("/pkg/snippets/leptos_dom-68e8edfe5e6c8b92/inline0.js", |_, _| {
let mut headers = Headers::new();
headers.set("Content-Type", "text/javascript")?;
let body = ResponseBody::Body(include_str!("../pkg/snippets/leptos_dom-68e8edfe5e6c8b92/inline0.js").as_bytes().to_vec());
Ok(
Response::from_body(body)?
.with_headers(headers)
)
})
.get(&format!("{PKG_PATH}_bg.wasm"), |_, _| {
let mut headers = Headers::new();
headers.set("Content-Type", "application/wasm")?;
let body = ResponseBody::Body(include_bytes!("../pkg/counter_worker_bg.wasm").to_vec());
Ok(
Response::from_body(body)?
.with_headers(headers)
)
})
.get("/worker-version", |_, ctx| {
let version = ctx.var("WORKERS_RS_VERSION")?.to_string();
Response::ok(version)
})
.run(req, env)
.await
}
}
}
fn render_html_page(body: &str) -> String {
format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="{PKG_PATH}.js">
<link rel="preload" href="{PKG_PATH}_bg.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '{PKG_PATH}.js'; init('{PKG_PATH}_bg.wasm').then(hydrate);</script>
</head>
<body>
{body}
</body>
</html>"#
)
}

View File

@@ -0,0 +1,9 @@
name = "" # todo
main = "build/worker/shim.mjs"
compatibility_date = "2022-01-20"
[vars]
WORKERS_RS_VERSION = "0.0.11"
[build]
command = "cargo install -q worker-build --version 0.0.7 && worker-build --release"