From d647e40d49dcba512e54cbfa629550db0900c5ee Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Sat, 23 Jul 2022 19:56:32 +0100 Subject: [PATCH] Define main embedded function script as a JavaScript module --- lib/src/fnc/script/main.rs | 23 +++++++++++------------ lib/src/sql/function.rs | 2 +- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/lib/src/fnc/script/main.rs b/lib/src/fnc/script/main.rs index d2ceeb94..e6ee957f 100644 --- a/lib/src/fnc/script/main.rs +++ b/lib/src/fnc/script/main.rs @@ -3,13 +3,16 @@ use super::executor::Executor; use crate::ctx::Context; use crate::err::Error; use crate::sql::value::Value; +use js::Function; use js::Promise; +use js::Rest; +use js::This; pub async fn run( ctx: &Context<'_>, + doc: Option<&Value>, src: &str, arg: Vec, - doc: Option<&Value>, ) -> Result { // Check the context if ctx.is_done() { @@ -23,12 +26,8 @@ pub async fn run( let ctx = js::Context::full(&run).unwrap(); // Enable async code in the runtime run.spawn_executor(&exe).detach(); - // Convert the arguments to JavaScript - let args = Value::from(arg); - // Convert the current document to JavaScript - let this = doc.map_or(&Value::None, |v| v); // Create the main function structure - let src = format!("(async function() {{ {} }}).apply(self, args)", src); + let src = format!("export async function main() {{ {} }}", src); // Attempt to execute the script let res: Result, js::Error> = ctx.with(|ctx| { // Get the context global object @@ -39,12 +38,12 @@ pub async fn run( global.init_def::().unwrap(); // Register the Uuid type as a global class global.init_def::().unwrap(); - // Register the document as a global object - global.prop("self", this).unwrap(); - // Register the args as a global object - global.prop("args", args).unwrap(); - // Attempt to execute the script - ctx.eval(src) + // Attempt to compile the script + let res = ctx.compile("script", src)?; + // Attempt to fetch the main export + let fnc = res.get::<_, Function>("main")?; + // Execute the main function + fnc.call((This(doc), Rest(arg))) }); // Return the script result let res = match res { diff --git a/lib/src/sql/function.rs b/lib/src/sql/function.rs index 5f3edab2..92c154ea 100644 --- a/lib/src/sql/function.rs +++ b/lib/src/sql/function.rs @@ -138,7 +138,7 @@ impl Function { for v in x { a.push(v.compute(ctx, opt, txn, doc).await?); } - fnc::script::run(ctx, s, a, doc).await + fnc::script::run(ctx, doc, s, a).await } #[cfg(not(feature = "scripting"))] {