chipa_webhooks/
template.rs1use std::sync::{Arc, RwLock};
2
3use handlebars::Handlebars;
4use serde_json::Value;
5
6use crate::error::WebhookError;
7
8#[derive(Clone)]
9pub struct TemplateEngine {
10 hbs: Arc<RwLock<Handlebars<'static>>>,
11}
12
13impl TemplateEngine {
14 pub fn new() -> Self {
15 let mut hbs = Handlebars::new();
16 hbs.set_strict_mode(false);
17 Self {
18 hbs: Arc::new(RwLock::new(hbs)),
19 }
20 }
21
22 pub fn register(&self, name: &str, template: &str) -> Result<(), WebhookError> {
23 self.hbs
24 .write()
25 .unwrap()
26 .register_template_string(name, template)
27 .map_err(WebhookError::from)
28 }
29
30 pub fn update(&self, name: &str, template: &str) -> Result<(), WebhookError> {
32 self.register(name, template)
33 }
34
35 pub fn remove(&self, name: &str) {
36 self.hbs.write().unwrap().unregister_template(name);
37 }
38
39 pub fn render(&self, name: &str, data: &Value) -> Result<String, WebhookError> {
40 let hbs = self.hbs.read().unwrap();
41 if !hbs.has_template(name) {
42 return Err(WebhookError::TemplateNotFound(name.to_owned()));
43 }
44 hbs.render(name, data).map_err(WebhookError::from)
45 }
46
47 pub fn has_template(&self, name: &str) -> bool {
48 self.hbs.read().unwrap().has_template(name)
49 }
50}
51
52impl Default for TemplateEngine {
53 fn default() -> Self {
54 Self::new()
55 }
56}