log_analyzer/models/
format.rs1use anyhow::{Result, anyhow};
2use regex::Regex;
3use serde::{Serialize, Deserialize};
4
5
6#[derive(Serialize, Deserialize, Clone, Debug)]
7pub struct Format {
8 pub alias: String,
9 pub regex: String
10}
11
12
13
14impl Format {
15 pub fn new(alias: &str, regex: &str) -> Result<Self> {
16 if alias.is_empty() || regex.is_empty() {
17 return Err(anyhow!("Error when creating new format.\nPlease review alias and regex are not empty"));
18 }
19
20 let re = Regex::new(regex);
21 match re {
22 Ok(_) => Ok(Format{alias: alias.to_string(), regex : regex.to_string()}),
23 Err(_) => Err(anyhow!("Could not compile regex.\nPlease review regex syntax"))
24 }
25 }
26}
27
28#[cfg(test)]
29mod tests {
30 use super::*;
31
32 #[test]
33 fn serialize() {
34 let format = Format::new(&"All".to_string(), &"(?P<PAYLOAD>.*)".to_string()).unwrap();
35 let json = serde_json::to_string(&format);
36 assert!(json.is_ok())
37 }
38
39 #[test]
40 fn deserialize() {
41 let json =r#"{"alias":"All","regex":"(?P<PAYLOAD>.*)"}"#;
42
43 let format: Result<Format, serde_json::Error> = serde_json::from_str(json);
44 assert!(format.is_ok())
45 }
46}