Skip to content

Commit

Permalink
start work towards a non-exclusively borrowed RequestInfo when execut…
Browse files Browse the repository at this point in the history
…ing queries

see #338
  • Loading branch information
lovasoa committed May 30, 2024
1 parent cef4066 commit 039495b
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion src/webserver/request_variables.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::collections::{hash_map::Entry, HashMap};
use std::{
cell::{Ref, RefCell},
collections::{hash_map::Entry, HashMap},
};

use super::http::SingleOrVec;

Expand All @@ -25,3 +28,41 @@ pub fn param_map<PAIRS: IntoIterator<Item = (String, String)>>(values: PAIRS) ->
map
})
}

/// This holds both the base variables set by URL parameters or form submission values in the initial
/// HTTP request,
/// and potential additional variables set by the programmer.
/// The same variable can be defined multiple times if there are multiple nested `run_sql` calls
struct RequestVariables {
root_variables: ParamMap,
set_variables: RefCell<Vec<ParamMap>>,
}

impl RequestVariables {
fn new(root_variables: ParamMap) -> Self {
RequestVariables {
root_variables,
set_variables: RefCell::new(Vec::new()),
}
}

pub fn edit<R>(&self, name: String, f: impl FnOnce(Entry<'_, String, SingleOrVec>) -> R) -> R {
let mut vars_list = self.set_variables.borrow_mut();
if vars_list.is_empty() {
vars_list.push(ParamMap::new());
}
let vars = vars_list.last_mut().unwrap();
f(vars.entry(name))
}

pub fn read_value<R>(&self, name: &str, f: impl FnOnce(Option<&SingleOrVec>) -> R) -> R {
let var_list = &self.set_variables.borrow();
let val = var_list
.iter()
.rev()
.flat_map(|m| m.get(name))
.next()
.or_else(|| self.root_variables.get(name));
f(val)
}
}

0 comments on commit 039495b

Please sign in to comment.