-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(wip): refactor parser selector into a format file
- Loading branch information
1 parent
c34ae7b
commit 53070ce
Showing
3 changed files
with
71 additions
and
25 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
use serde_json::Value; | ||
|
||
use crate::parser::{ | ||
extractors::{extract_html, extract_json, get_value_type}, | ||
ExtractionResult, ExtractorConfig, ExtractorError, | ||
}; | ||
|
||
/// Trait for data format extractors | ||
pub trait FormatExtractor { | ||
fn validate_input(&self, data: &Value) -> Result<(), ExtractorError>; | ||
fn extract( | ||
&self, | ||
data: &Value, | ||
config: &ExtractorConfig, | ||
) -> Result<ExtractionResult, ExtractorError>; | ||
} | ||
|
||
pub struct JsonExtractor; | ||
pub struct HtmlExtractor; | ||
|
||
impl FormatExtractor for JsonExtractor { | ||
fn validate_input(&self, data: &Value) -> Result<(), ExtractorError> { | ||
if !matches!(data, Value::Object(_) | Value::Array(_)) { | ||
return Err(ExtractorError::TypeMismatch { | ||
expected: "object or array".to_string(), | ||
actual: get_value_type(data).to_string(), | ||
}); | ||
} | ||
Ok(()) | ||
} | ||
|
||
fn extract( | ||
&self, | ||
data: &Value, | ||
config: &ExtractorConfig, | ||
) -> Result<ExtractionResult, ExtractorError> { | ||
extract_json(data, config) | ||
} | ||
} | ||
|
||
impl FormatExtractor for HtmlExtractor { | ||
fn validate_input(&self, data: &Value) -> Result<(), ExtractorError> { | ||
if !matches!(data, Value::String(_)) { | ||
return Err(ExtractorError::TypeMismatch { | ||
expected: "string".to_string(), | ||
actual: get_value_type(data).to_string(), | ||
}); | ||
} | ||
Ok(()) | ||
} | ||
|
||
fn extract( | ||
&self, | ||
data: &Value, | ||
config: &ExtractorConfig, | ||
) -> Result<ExtractionResult, ExtractorError> { | ||
data.as_str().map(|s| extract_html(s, config)).unwrap_or_else(|| unreachable!()) | ||
} | ||
} |
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