Skip to content

Commit

Permalink
feat: handle async functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Valerioageno committed Apr 25, 2024
1 parent 8595584 commit 2951ed2
Showing 1 changed file with 74 additions and 1 deletion.
75 changes: 74 additions & 1 deletion src/ssr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,26 @@ where

// TODO: transform this into an iterator
for key in self.fn_map.keys() {
let result = match self.fn_map[key].call(scope, undef, &[params]) {
let render_fn = self.fn_map[key];

let mut result = match render_fn.call(scope, undef, &[params]) {
Some(val) => val,
None => return Err("Failed to call function"),
};

if result.is_promise() {
let promise = match v8::Local::<v8::Promise>::try_from(result) {
Ok(val) => val,
Err(_) => return Err("Failed to cast main function to promise"),
};

while promise.state() == v8::PromiseState::Pending {
scope.perform_microtask_checkpoint();
}

result = promise.result(scope);
}

let result = match result.to_string(scope) {
Some(val) => val,
None => return Err("Failed to parse the result to string"),
Expand Down Expand Up @@ -282,4 +297,62 @@ mod tests {

assert_eq!(js2.render_to_string(None).unwrap(), "I don't accept params");
}

#[test]
fn entry_point_is_async() {
init_test();

let mut js = Ssr::from(
r##"var SSR = {x: async () => "<html></html>"};"##.to_string(),
"SSR",
)
.unwrap();

assert_eq!(js.render_to_string(None).unwrap(), "<html></html>");
assert_eq!(
js.render_to_string(Some(r#"{"Hello world"}"#)).unwrap(),
"<html></html>"
);
}

#[test]
fn entry_point_is_async_with_params() {
init_test();

let mut js = Ssr::from(
r##"var SSR = {x: async (params) => "These are our parameters: " + params};"##
.to_string(),
"SSR",
)
.unwrap();

assert_eq!(
js.render_to_string(Some(r#"{"Hello world"}"#)).unwrap(),
"These are our parameters: {\"Hello world\"}"
);
}

#[test]
fn entry_point_is_async_with_nested_async() {
init_test();

let mut js = Ssr::from(
r##"
const asyncFn = async () => {
return "Hello world"
}
var SSR = {x: async () => {
return await asyncFn()
}};
"##
.to_string(),
"SSR",
)
.unwrap();

assert_eq!(
js.render_to_string(Some(r#"{"Hello world"}"#)).unwrap(),
"Hello world"
);
}
}

0 comments on commit 2951ed2

Please sign in to comment.