event_template.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. use crate::util::get_tera;
  2. use tera::Context;
  3. pub struct EventTemplate {
  4. tera_context: Context,
  5. }
  6. pub struct EventRenderContext {
  7. pub input_deserializer: Option<String>,
  8. pub output_deserializer: Option<String>,
  9. pub error_deserializer: String,
  10. pub event: String,
  11. pub event_ty: String,
  12. pub prefix: String,
  13. }
  14. #[allow(dead_code)]
  15. impl EventTemplate {
  16. pub fn new() -> Self {
  17. EventTemplate {
  18. tera_context: Context::new(),
  19. }
  20. }
  21. pub fn render(&mut self, ctx: EventRenderContext, index: usize) -> Option<String> {
  22. self.tera_context.insert("index", &index);
  23. let event_func_name = format!("{}{}", ctx.event_ty, ctx.event);
  24. self
  25. .tera_context
  26. .insert("event_func_name", &event_func_name);
  27. self
  28. .tera_context
  29. .insert("event_name", &format!("{}.{}", ctx.prefix, ctx.event_ty));
  30. self.tera_context.insert("event", &ctx.event);
  31. self
  32. .tera_context
  33. .insert("has_input", &ctx.input_deserializer.is_some());
  34. match ctx.input_deserializer {
  35. None => {},
  36. Some(ref input) => self
  37. .tera_context
  38. .insert("input_deserializer", &format!("{}.{}", ctx.prefix, input)),
  39. }
  40. let has_output = ctx.output_deserializer.is_some();
  41. self.tera_context.insert("has_output", &has_output);
  42. match ctx.output_deserializer {
  43. None => self.tera_context.insert("output_deserializer", "void"),
  44. Some(ref output) => self
  45. .tera_context
  46. .insert("output_deserializer", &format!("{}.{}", ctx.prefix, output)),
  47. }
  48. self.tera_context.insert(
  49. "error_deserializer",
  50. &format!("{}.{}", ctx.prefix, ctx.error_deserializer),
  51. );
  52. let tera = get_tera("ts_event");
  53. match tera.render("event_template.tera", &self.tera_context) {
  54. Ok(r) => Some(r),
  55. Err(e) => {
  56. log::error!("{:?}", e);
  57. None
  58. },
  59. }
  60. }
  61. }