1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
pub mod caps;
pub mod extract;
pub mod replace;
pub mod set;
pub mod shorten;
pub mod trim;
pub use self::{
caps::Caps, extract::Extract, replace::Replace, set::Set, shorten::Shorten, trim::Trim,
};
use async_trait::async_trait;
use std::fmt::Debug;
use url::Url;
use super::{result::TransformResult, Transform};
use crate::{
action::transform::error::{TransformError, TransformErrorKind},
entry::Entry,
error::InvalidUrlError,
sink::message::Message,
utils::OptionExt,
};
pub trait TransformField: Debug + Send + Sync {
type Err: Into<TransformErrorKind>;
fn transform_field(&self, old_val: Option<&str>) -> Result<TransformResult<String>, Self::Err>;
}
#[derive(Debug)]
pub struct TransformFieldWrapper<T>
where
T: TransformField,
{
pub field: Field,
pub transformator: T,
}
#[async_trait]
impl<T> Transform for TransformFieldWrapper<T>
where
T: TransformField,
{
async fn transform(&self, mut entry: Entry) -> Result<Vec<Entry>, TransformError> {
let old_val = match self.field {
Field::Title => entry.msg.title.take(),
Field::Body => entry.msg.body.take(),
Field::Link => entry.msg.link.take().map(|u| u.to_string()),
Field::Id => entry.id.take().map(|id| id.0),
Field::ReplyTo => entry.reply_to.take().map(|id| id.0),
Field::RawContets => entry.raw_contents.take(),
};
let new_val = self
.transformator
.transform_field(old_val.as_deref())
.map_err(|kind| TransformError {
kind: kind.into(),
original_entry: entry.clone(),
})?;
let final_val = new_val.get(|| old_val);
let new_entry = match self.field {
Field::Title => Entry {
msg: Message {
title: final_val,
..entry.msg
},
..entry
},
Field::Body => Entry {
msg: Message {
body: final_val,
..entry.msg
},
..entry
},
Field::Link => {
let link = final_val.try_map(|s| {
Url::try_from(s.as_str()).map_err(|e| TransformError {
kind: TransformErrorKind::FieldLinkTransformInvalidUrl(InvalidUrlError(
e, s,
)),
original_entry: entry.clone(),
})
})?;
Entry {
msg: Message { link, ..entry.msg },
..entry
}
}
Field::Id => Entry {
id: final_val.map(Into::into),
..entry
},
Field::ReplyTo => Entry {
reply_to: final_val.map(Into::into),
..entry
},
Field::RawContets => Entry {
raw_contents: final_val,
..entry
},
};
Ok(vec![new_entry])
}
}
#[derive(Clone, Copy, Debug)]
pub enum Field {
Title,
Body,
Link,
Id,
ReplyTo,
RawContets,
}