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 31f12f7
Showing 1 changed file with 84 additions and 6 deletions.
90 changes: 84 additions & 6 deletions src/ssr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,17 +147,37 @@ 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 result = match render_fn.call(scope, undef, &[params]) {
Some(val) => val,
None => return Err("Failed to call function"),
};

let result = match result.to_string(scope) {
Some(val) => val,
None => return Err("Failed to parse the result to string"),
};
if result.is_promise() {
dbg!("This is a promise");

let promise = v8::Local::<v8::Promise>::try_from(result).unwrap();

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

let result = promise.result(scope);
let result = match result.to_string(scope) {
Some(val) => val,
None => return Err("Failed to parse the result to string"),
};

rendered = format!("{}{}", rendered, result.to_rust_string_lossy(scope));
} else {
let result = match result.to_string(scope) {
Some(val) => val,
None => return Err("Failed to parse the result to string"),
};

rendered = format!("{}{}", rendered, result.to_rust_string_lossy(scope));
rendered = format!("{}{}", rendered, result.to_rust_string_lossy(scope));
}
}

Ok(rendered)
Expand Down Expand Up @@ -282,4 +302,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 31f12f7

Please sign in to comment.