migration to JS engine #1

Merged
akulij merged 131 commits from dev into main 2025-05-31 08:49:52 +00:00
2 changed files with 51 additions and 0 deletions
Showing only changes of commit ff7f317ae5 - Show all commits

View File

@ -1,3 +1,4 @@
pub mod db;
use std::collections::HashMap;
use crate::db::raw_calls::RawCallError;

50
src/botscript/db.rs Normal file
View File

@ -0,0 +1,50 @@
use std::sync::RwLock;
use quickjs_rusty::context::Context;
use quickjs_rusty::serde::{from_js, to_js};
use quickjs_rusty::{utils::create_empty_object, OwnedJsObject, OwnedJsValue as JsValue};
use crate::db::raw_calls::RawCall;
use crate::db::DB;
use super::ScriptError;
pub fn attach_db_obj(c: &Context, o: &mut OwnedJsObject, db: &DB) -> Result<(), ScriptError> {
let dbobj = JsValue::new(o.context(), create_empty_object(o.context())?)
.try_into_object()
.expect("the created object was not an object :/");
let db: std::sync::Arc<RwLock<DB>> = std::sync::Arc::new(RwLock::new(db.clone()));
let dbbox = Box::new(db);
let db: &'static _ = Box::leak(dbbox);
let find_one = c.create_callback(
|collection: String, q: OwnedJsObject| -> Result<_, ScriptError> {
let query: serde_json::Value = match from_js(q.context(), &q) {
Ok(q) => q,
Err(_) => todo!(),
};
let db = db.clone();
let value = futures::executor::block_on(
db.write()
.expect("failed to gain write acces to db (probably RwLock is poisoned)")
.find_one(&collection, query),
)?;
let ret = match value {
Some(v) => Some(to_js(q.context(), &v)?),
None => None,
};
Ok(ret)
},
)?;
let find_one = JsValue::from((unsafe { c.context_raw() }, find_one));
dbobj.set_property("find_one", find_one)?;
o.set_property("db", dbobj.into_value())?;
Ok(())
}