Last active
March 1, 2019 21:46
-
-
Save kestred/6cac1149b072228bd398e2c60e3c7871 to your computer and use it in GitHub Desktop.
Example juniper batching in synchronous call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// use other::stuff::{not_a_working_example}; | |
use std::cell::RefCell; | |
use std::rc::Rc; | |
graphql_object!(Queries: () |&self| { | |
field many_rules() -> Vec<ProductRules> { | |
// .... | |
} | |
}); | |
mod accounting { | |
#[derive(GraphQLObject)] | |
struct ProductRules { | |
// ... Some data ... | |
} | |
} | |
#[derive(Clone)] | |
pub struct ProductRulesBatch { | |
ids: Vec<ProductId>, | |
data: RefCell<BTreeMap<AccountChartId, BTreeMap<ProductId, accounting::ProductRules>>>, | |
ctx: Cache, | |
} | |
impl ProductRulesBatch { | |
pub fn new(ctx: Cache, ids: Vec<ProductId>) -> ProductRulesBatch { | |
ProductRulesBatch { ids, data: RefCell::new(BTreeMap::new()), ctx, } | |
} | |
pub fn load(&self, product_id: ProductId, chart_id: AccountChartId) -> Result<accounting::ProductRules, Error> { | |
if !self.data.borrow().contains_key(&chart_id) { | |
let request = accounting::GetProductRulesMultiple { chart_id: chart_id.clone(), product_ids: self.ids.to_vec() }; | |
let rules = self.ctx.accounting().get_product_rules_multiple(&self.ctx.context, request)?; | |
let mut data = BTreeMap::new(); | |
for rule in rules { | |
data.insert(rule.product_id.clone(), rule); | |
} | |
self.data.borrow_mut().insert(chart_id.clone(), data); | |
} | |
self.data.borrow() | |
.get(&chart_id) | |
.and_then(|data| data.get(&product_id)) | |
.cloned() | |
.ok_or_else(|| { | |
let msg = format!("Missing product rules for chart {}, product {}", &chart_id, &product_id); | |
Error::from(ErrorKind::Internal.debug_message(msg)) | |
}) | |
} | |
} | |
#[derive(Clone)] | |
pub struct ProductRules { | |
pub id: ProductId, | |
batch: Rc<ProductRulesBatch>, | |
} | |
impl ProductRules { | |
pub fn ids(ctx: &Cache, ids: Vec<ProductId>) -> Vec<Self> { | |
let batch = Rc::new(ProductRulesBatch::new(ctx.clone(), ids.clone())); | |
ids.into_iter().map(|id| ProductRules { id, batch: batch.clone() }).collect() | |
} | |
pub fn get(&self, chart_id: AccountChartId) -> Result<accounting::ProductRules, Error> { | |
self.batch.load(self.id.clone(), chart_id) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment