|
| 1 | +use crate::js_value::JsonValue; |
| 2 | +use rquickjs::class::Trace; |
| 3 | +use rquickjs::Class; |
| 4 | +use rquickjs::Ctx; |
| 5 | +use rquickjs::JsLifetime; |
| 6 | +use rquickjs::Result; |
| 7 | +use std::collections::BTreeMap; |
| 8 | +use std::ops::Deref; |
| 9 | +use std::sync::Arc; |
| 10 | +use std::sync::Mutex; |
| 11 | + |
| 12 | +#[derive(Clone, Default, JsLifetime)] |
| 13 | +pub struct KVStore { |
| 14 | + data: Arc<Mutex<BTreeMap<String, JsonValue>>>, |
| 15 | +} |
| 16 | + |
| 17 | +impl KVStore { |
| 18 | + pub fn init(&self, ctx: &Ctx<'_>) { |
| 19 | + let globals = ctx.globals(); |
| 20 | + let _ = Class::<FlowStore>::define(&globals); |
| 21 | + self.store_as_userdata(ctx) |
| 22 | + } |
| 23 | + |
| 24 | + pub fn get(&self, key: &str) -> JsonValue { |
| 25 | + let data = self.data.lock().unwrap(); |
| 26 | + data.get(key).cloned().unwrap_or(JsonValue::Null) |
| 27 | + } |
| 28 | + |
| 29 | + pub fn insert(&self, key: impl Into<String>, value: impl Into<JsonValue>) { |
| 30 | + match value.into() { |
| 31 | + JsonValue::Null => self.remove(&key.into()), |
| 32 | + value => { |
| 33 | + let mut data = self.data.lock().unwrap(); |
| 34 | + data.insert(key.into(), value); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + pub fn remove(&self, key: &str) { |
| 40 | + let mut data = self.data.lock().unwrap(); |
| 41 | + data.remove(key); |
| 42 | + } |
| 43 | + |
| 44 | + fn store_as_userdata(&self, ctx: &Ctx<'_>) { |
| 45 | + let _ = ctx.store_userdata(self.clone()); |
| 46 | + } |
| 47 | + |
| 48 | + fn get_from_userdata(ctx: &Ctx<'_>) -> Self { |
| 49 | + match ctx.userdata::<Self>() { |
| 50 | + None => { |
| 51 | + let store = KVStore::default(); |
| 52 | + store.store_as_userdata(ctx); |
| 53 | + store |
| 54 | + } |
| 55 | + Some(userdata) => userdata.deref().clone(), |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +#[derive(Clone, Trace, JsLifetime)] |
| 61 | +#[rquickjs::class(frozen)] |
| 62 | +pub struct FlowStore {} |
| 63 | + |
| 64 | +#[rquickjs::methods] |
| 65 | +impl<'js> FlowStore { |
| 66 | + #[qjs(constructor)] |
| 67 | + fn new(_ctx: Ctx<'js>) -> Result<FlowStore> { |
| 68 | + Ok(FlowStore {}) |
| 69 | + } |
| 70 | + |
| 71 | + fn get(&self, ctx: Ctx<'js>, key: String) -> Result<JsonValue> { |
| 72 | + let data = KVStore::get_from_userdata(&ctx); |
| 73 | + Ok(data.get(&key)) |
| 74 | + } |
| 75 | +} |
0 commit comments