Skip to content

Commit

Permalink
Ssr lib return results (#17)
Browse files Browse the repository at this point in the history
* feat: return Result from struct methods

* doc: update README crate version

* doc: update doc

* fix: prevent stale pipeline check
  • Loading branch information
Valerioageno authored Mar 3, 2024
1 parent c2af223 commit b671f98
Show file tree
Hide file tree
Showing 11 changed files with 221 additions and 92 deletions.
63 changes: 57 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ The project aims to enable server side rendering on rust servers in the simplest

It use an embedded version of the v8 javascript engine (<a href="https://github.com/denoland/rusty_v8" target="_blank">rusty_v8</a>) to parse and evaluate a built bundle file and return a string with the rendered html.

Currently it works with Webpack bundler v5.65.0; check it out <a href="https://github.com/Valerioageno/reactix" target="_blank">here</a> a full project who use this crate.
Currently it works with Webpack bundler v5.65.0.

## Getting started

Add this to your `Cargo.toml`:

```toml
[dependencies]
ssr_rs = "0.2.3"
ssr_rs = "0.3.0"
```

## Example
Expand All @@ -32,9 +32,9 @@ fn main() {

let source = read_to_string("./path/to/build.js").unwrap();

let mut js = Ssr::new(&source, "entryPoint");
let mut js = Ssr::new(&source, "entryPoint").unwrap();

let html = js.render_to_string(None);
let html = js.render_to_string(None).unwrap();

assert_eq!(html, "<!doctype html><html>...</html>".to_string());
}
Expand All @@ -60,14 +60,65 @@ fn main() {

let source = read_to_string("./path/to/build.js").unwrap();

let mut js = Ssr::new(&source, "entryPoint");
let mut js = Ssr::new(&source, "entryPoint").unwrap();

let html = js.render_to_string(Some(&props));
let html = js.render_to_string(Some(&props)).unwrap();

assert_eq!(html, "<!doctype html><html>...</html>".to_string());
}
```

## Example with actix-web

> Examples with different web frameworks are available in the <a href="https://github.com/Valerioageno/ssr-rs/blob/main/examples" target="_blank">examples</a> folder.
Even though the V8 engine allows accessing the same `isolate` from different threads that is forbidden by this crate for two reasons:

1. rusty_v8 library have not implemented yet the V8 Locker API. Accessing Ssr struct from a different thread will make the V8 engine to panic.
2. Rendering HTML does not need shared state across threads.

For this reason parallel computation is a better choice. Following actix-web setup:

```rust
use actix_web::{get, http::StatusCode, App, HttpResponse, HttpServer};
use std::cell::RefCell;
use std::fs::read_to_string;

use ssr_rs::Ssr;

thread_local! {
static SSR: RefCell<Ssr<'static, 'static>> = RefCell::new(
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
).unwrap()
)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {

Ssr::create_platform();

HttpServer::new(|| {
App::new()
.service(index)
})
.bind("127.0.0.1:8080")?
.run()
.await
}

#[get("/")]
async fn index() -> HttpResponse {
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None).unwrap());

HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(result)
}
```

## Contributing

Any helps or suggestions will be appreciated.
Expand Down
6 changes: 3 additions & 3 deletions examples/actix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ thread_local! {
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
)
).unwrap()
)
}

Expand All @@ -37,9 +37,9 @@ async fn main() -> std::io::Result<()> {
#[get("/")]
async fn index() -> HttpResponse {
let start = Instant::now();
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None));
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None).unwrap());
println!("Elapsed: {:?}", start.elapsed());
// This is a benchmark example. Please refer to examples/shared_ssr.rs for a better solution.

HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(result)
Expand Down
4 changes: 2 additions & 2 deletions examples/actix_with_initial_props.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ thread_local! {
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
)
).unwrap()
)
}

Expand Down Expand Up @@ -42,5 +42,5 @@ async fn index() -> HttpResponse {

HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(mock_props))))
.body(SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(mock_props)).unwrap()))
}
4 changes: 2 additions & 2 deletions examples/axum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ thread_local! {
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
)
).unwrap()
)
}

Expand All @@ -29,5 +29,5 @@ async fn root() -> Html<String> {
let start = Instant::now();
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None));
println!("Elapsed: {:?}", start.elapsed());
Html(result)
Html(result.unwrap())
}
4 changes: 2 additions & 2 deletions examples/multi-thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ thread_local! {
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
)
).unwrap()
)
}

Expand All @@ -23,7 +23,7 @@ fn main() {
let start = Instant::now();
println!(
"result: {}",
SSR.with(|ssr| ssr.borrow_mut().render_to_string(None))
SSR.with(|ssr| ssr.borrow_mut().render_to_string(None).unwrap())
);
println!(
"Thread #{i} finished! - Elapsed time: {:?}",
Expand Down
4 changes: 2 additions & 2 deletions examples/rocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ thread_local! {
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
)
).unwrap()
)
}

Expand All @@ -21,7 +21,7 @@ fn index() -> content::RawHtml<String> {
let start = Instant::now();
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None));
println!("Elapsed: {:?}", start.elapsed());
content::RawHtml(result)
content::RawHtml(result.unwrap())
}

#[launch]
Expand Down
6 changes: 3 additions & 3 deletions examples/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ fn main() {
Ssr::create_platform();

// This takes roughly 40ms
let mut ssr = Ssr::from(source, "SSR");
let mut ssr = Ssr::from(source, "SSR").unwrap();

// This takes roughly 0.5ms
println!("{}", ssr.render_to_string(None));
println!("{}", ssr.render_to_string(None));
println!("{}", ssr.render_to_string(None).unwrap());
println!("{}", ssr.render_to_string(None).unwrap());
}
4 changes: 2 additions & 2 deletions examples/tide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ thread_local! {
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
)
).unwrap()
)
}

Expand All @@ -31,7 +31,7 @@ async fn return_html(_req: Request<()>) -> tide::Result {
println!("Elapsed: {:?}", start.elapsed());

let response = Response::builder(200)
.body(html)
.body(html.unwrap())
.content_type(tide::http::mime::HTML)
.build();

Expand Down
4 changes: 2 additions & 2 deletions examples/warp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ thread_local! {
Ssr::from(
read_to_string("./client/dist/ssr/index.js").unwrap(),
"SSR"
)
).unwrap()
)
}

Expand All @@ -22,7 +22,7 @@ async fn main() {
let start = Instant::now();
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None));
println!("Elapsed: {:?}", start.elapsed());
Response::builder().body(result)
Response::builder().body(result.unwrap())
});

let css = warp::path("styles").and(warp::fs::dir("./client/dist/ssr/styles/"));
Expand Down
62 changes: 55 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
//!
//! It use an embedded version of the v8 javascript engine (<a href="https://github.com/denoland/rusty_v8" target="_blank">rusty_v8</a>) to parse and evaluate a built bundle file and return a string with the rendered html.
//!
//! Currently it works with Webpack bundler v4.44.2; check it out <a href="https://github.com/Valerioageno/reactix" target="_blank">here</a> a full project who use this crate.
//! Currently it works with Webpack bundler v4.44.2.
//!
//! # Gettin started
//! # Getting started
//! ```toml
//! [dependencies]
//! ssr_rs = "0.3.0"
Expand All @@ -28,9 +28,9 @@
//!
//! let source = read_to_string("./path/to/build.js").unwrap();
//!
//! let mut js = Ssr::from(source, "entryPoint");
//! let mut js = Ssr::from(source, "entryPoint").unwrap();
//!
//! let html = js.render_to_string(None);
//! let html = js.render_to_string(None).unwrap();
//!
//! assert_eq!(html, "<!doctype html><html>...</html>".to_string());
//! }
Expand All @@ -56,14 +56,62 @@
//!
//! let source = read_to_string("./path/to/build.js").unwrap();
//!
//! let mut js = Ssr::from(source, "entryPoint");
//! let mut js = Ssr::from(source, "entryPoint").unwrap();
//!
//! let html = js.render_to_string(Some(&props));
//! let html = js.render_to_string(Some(&props)).unwrap();
//!
//! assert_eq!(html, "<!doctype html><html>...</html>".to_string());
//! }
//!```
//!
//! # Example with actix-web
//!
//! > Examples with different web frameworks are available in the <a href="https://github.com/Valerioageno/ssr-rs/blob/main/examples" target="_blank">examples</a> folder.
//!
//! Even though the V8 engine allows accessing the same `isolate` from different threads that is forbidden by this crate for two reasons:
//! 1. rusty_v8 library have not implemented yet the V8 Locker API. Accessing Ssr struct from a different thread will make the V8 engine to panic.
//! 2. Rendering HTML does not need shared state across threads.
//!
//! For this reason parallel computation is a better choice. Following actix-web setup:
//!
//! ```no_run
//! use actix_web::{get, http::StatusCode, App, HttpResponse, HttpServer};
//! use std::cell::RefCell;
//! use std::fs::read_to_string;
//!
//! use ssr_rs::Ssr;
//!
//! thread_local! {
//! static SSR: RefCell<Ssr<'static, 'static>> = RefCell::new(
//! Ssr::from(
//! read_to_string("./client/dist/ssr/index.js").unwrap(),
//! "SSR"
//! ).unwrap()
//! )
//!}
//!
//! #[actix_web::main]
//!async fn main() -> std::io::Result<()> {
//! Ssr::create_platform();
//!
//! HttpServer::new(|| {
//! App::new()
//! .service(index)
//! })
//! .bind("127.0.0.1:8080")?
//! .run()
//! .await
//! }
//!
//! #[get("/")]
//! async fn index() -> HttpResponse {
//! let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None).unwrap());
//!
//! HttpResponse::build(StatusCode::OK)
//! .content_type("text/html; charset=utf-8")
//! .body(result)
//! }
//!```
mod ssr;

pub use ssr::Ssr;
Loading

0 comments on commit b671f98

Please sign in to comment.