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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use self::RenameRule::*;
use crate::{error::Error, request::Request, serde_request::from_request};
use async_trait::async_trait;
use cruet::Inflector;
use serde::Deserialize;
use std::str::FromStr;

///If a type implements this feature, it will provide a metadata that will help resolve the request to data of that type
#[async_trait]
pub trait Extractor<'de>: Deserialize<'de> {
    /// Metadata for Extractor type.
    fn metadata() -> &'de Metadata;

    /// Extract data from request.
    async fn extract(req: &'de mut Request) -> Result<Self, Error> {
        from_request(req, Self::metadata()).await
    }
    /// Extract data from request with a argument. This function used in macros internal.
    async fn extract_with_arg(req: &'de mut Request, _arg: &str) -> Result<Self, Error> {
        Self::extract(req).await
    }
}

/// Source for a field.
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
#[non_exhaustive]
pub enum SourceFrom {
    /// The field will extracted from url path param.
    Path,
    /// The field will extracted from url query.
    Query,
    /// The field will extracted from http header.
    Header,
    /// The field will extracted from http cookie.
    #[cfg(feature = "cookie")]
    Cookie,
    /// The field will extracted from http payload.
    Body,
}

impl FromStr for SourceFrom {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "path" => Ok(Self::Path),
            "query" => Ok(Self::Query),
            "header" => Ok(Self::Header),
            #[cfg(feature = "cookie")]
            "cookie" => Ok(Self::Cookie),
            "body" => Ok(Self::Body),
            _ => Err(Error::Other(format!("invalid source from `{input}`"))),
        }
    }
}

/// Rename rule for a field.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[non_exhaustive]
pub enum RenameRule {
    /// Rename direct children to "lowercase" style.
    LowerCase,
    /// Rename direct children to "UPPERCASE" style.
    UpperCase,
    /// Rename direct children to "PascalCase" style, as typically used for
    /// enum variants.
    PascalCase,
    /// Rename direct children to "camelCase" style.
    CamelCase,
    /// Rename direct children to "snake_case" style, as commonly used for
    /// fields.
    SnakeCase,
    /// Rename direct children to "SCREAMING_SNAKE_CASE" style, as commonly
    /// used for constants.
    ScreamingSnakeCase,
    /// Rename direct children to "kebab-case" style.
    KebabCase,
    /// Rename direct children to "SCREAMING-KEBAB-CASE" style.
    ScreamingKebabCase,
}

impl FromStr for RenameRule {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        for (name, rule) in RENAME_RULES {
            if input == *name {
                return Ok(*rule);
            }
        }
        Err(Error::Other(format!("invalid rename rule: {input}")))
    }
}

static RENAME_RULES: &[(&str, RenameRule)] = &[
    ("lowercase", LowerCase),
    ("UPPERCASE", UpperCase),
    ("PascalCase", PascalCase),
    ("camelCase", CamelCase),
    ("snake_case", SnakeCase),
    ("SCREAMING_SNAKE_CASE", ScreamingSnakeCase),
    ("kebab-case", KebabCase),
    ("SCREAMING-KEBAB-CASE", ScreamingKebabCase),
];
impl RenameRule {
    /// Apply a renaming rule to an variant, returning the version expected in the source.
    pub fn rename(&self, name: impl AsRef<str>) -> String {
        let name = name.as_ref();
        match *self {
            PascalCase => name.to_pascal_case(),
            LowerCase => name.to_lowercase(),
            UpperCase => name.to_uppercase(),
            CamelCase => name.to_camel_case(),
            SnakeCase => name.to_snake_case(),
            ScreamingSnakeCase => SnakeCase.rename(name).to_ascii_uppercase(),
            KebabCase => SnakeCase.rename(name).replace('_', "-"),
            ScreamingKebabCase => ScreamingSnakeCase.rename(name).replace('_', "-"),
        }
    }
}

/// Source format for a source. This format is just means that field format, not the request mime type.
/// For example, the request is posted as form, but if the field is string as json format, it can be parsed as json.
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
#[non_exhaustive]
pub enum SourceParser {
    /// MulitMap parser.
    MultiMap,
    /// Json format.
    Json,
    /// Smart parser.
    Smart,
}

impl FromStr for SourceParser {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "multimap" => Ok(Self::MultiMap),
            "json" => Ok(Self::Json),
            "smart" => Ok(Self::Smart),
            _ => Err(Error::Other("invalid source format".to_owned())),
        }
    }
}

/// Struct's metadata information.
#[derive(Default, Clone, Debug)]
#[non_exhaustive]
pub struct Metadata {
    /// The name of this type.
    pub name: &'static str,
    /// Default sources of all fields.
    pub default_sources: Vec<Source>,
    /// Fields of this type.
    pub fields: Vec<Field>,
    /// Rename rule for all fields of this type.
    pub rename_all: Option<RenameRule>,
}

impl Metadata {
    /// Create a new metadata object.
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            default_sources: vec![],
            fields: vec![],
            rename_all: None,
        }
    }

    /// Sets the default sources list to a new value.
    pub fn default_sources(mut self, default_sources: Vec<Source>) -> Self {
        self.default_sources = default_sources;
        self
    }

    /// set all fields list to a new value.
    pub fn fields(mut self, fields: Vec<Field>) -> Self {
        self.fields = fields;
        self
    }

    /// Add a default source to default sources list.
    pub fn add_default_source(mut self, source: Source) -> Self {
        self.default_sources.push(source);
        self
    }

    /// Add a field to the fields list.
    pub fn add_field(mut self, field: Field) -> Self {
        self.fields.push(field);
        self
    }

    /// Rule for rename all fields of type.
    pub fn rename_all(mut self, rename_all: impl Into<Option<RenameRule>>) -> Self {
        self.rename_all = rename_all.into();
        self
    }

    /// Check is this type has body required.
    pub(crate) fn has_body_required(&self) -> bool {
        if self
            .default_sources
            .iter()
            .any(|s| s.from == SourceFrom::Body)
        {
            return true;
        }
        self.fields.iter().any(|f| f.has_body_required())
    }
}

/// Information about struct field.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Field {
    /// Field name.
    pub name: &'static str,
    /// Field flatten, this field will extracted from request.
    pub flatten: bool,
    /// Field sources.
    pub sources: Vec<Source>,
    /// Field aliaes.
    pub aliases: Vec<&'static str>,
    /// Field rename.
    pub rename: Option<&'static str>,
    /// Field metadata. This is used for nested extractible types.
    pub metadata: Option<&'static Metadata>,
}
impl Field {
    /// Create a new field with the given name and kind.
    pub fn new(name: &'static str) -> Self {
        Self::with_sources(name, vec![])
    }

    /// Create a new field with the given name and kind, and the given sources.
    pub fn with_sources(name: &'static str, sources: Vec<Source>) -> Self {
        Self {
            name,
            flatten: false,
            sources,
            aliases: vec![],
            rename: None,
            metadata: None,
        }
    }

    /// Sets the flatten to the given value.
    pub fn set_flatten(mut self, flatten: bool) -> Self {
        self.flatten = flatten;
        self
    }

    /// Sets the metadata to the field type.
    pub fn metadata(mut self, metadata: &'static Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Add a source to sources list.
    pub fn add_source(mut self, source: Source) -> Self {
        self.sources.push(source);
        self
    }

    /// Sets the aliases list to a new value.
    pub fn set_aliases(mut self, aliases: Vec<&'static str>) -> Self {
        self.aliases = aliases;
        self
    }

    /// Add a alias to aliases list.
    pub fn add_alias(mut self, alias: &'static str) -> Self {
        self.aliases.push(alias);
        self
    }

    /// Sets the rename to the given value.
    pub fn rename(mut self, rename: &'static str) -> Self {
        self.rename = Some(rename);
        self
    }

    /// Check is this field has body required.
    pub(crate) fn has_body_required(&self) -> bool {
        self.sources.iter().any(|s| s.from == SourceFrom::Body)
    }
}

/// Request source for extract data.
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub struct Source {
    /// The source from.
    pub from: SourceFrom,
    /// The parser used to parse data.
    pub parser: SourceParser,
}
impl Source {
    /// Create a new source from a string.
    pub fn new(from: SourceFrom, format: SourceParser) -> Self {
        Self {
            from,
            parser: format,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_source_from() {
        for (key, value) in [
            ("path", SourceFrom::Path),
            ("query", SourceFrom::Query),
            ("header", SourceFrom::Header),
            #[cfg(feature = "cookie")]
            ("cookie", SourceFrom::Cookie),
            ("body", SourceFrom::Body),
        ] {
            assert_eq!(key.parse::<SourceFrom>().unwrap(), value);
        }
        assert!("abcd".parse::<SourceFrom>().is_err());
    }

    #[test]
    fn test_parse_source_format() {
        for (key, value) in [
            ("multimap", SourceParser::MultiMap),
            ("json", SourceParser::Json),
        ] {
            assert_eq!(key.parse::<SourceParser>().unwrap(), value);
        }
        assert!("abcd".parse::<SourceParser>().is_err());
    }

    #[test]
    fn test_parse_rename_rule() {
        for (key, value) in RENAME_RULES {
            assert_eq!(key.parse::<RenameRule>().unwrap(), *value);
        }
        assert!("abcd".parse::<RenameRule>().is_err());
    }

    #[test]
    fn test_rename_rule() {
        assert_eq!(PascalCase.rename("rename_rule"), "RenameRule");
        assert_eq!(LowerCase.rename("RenameRule"), "renamerule");
        assert_eq!(UpperCase.rename("rename_rule"), "RENAME_RULE");
        assert_eq!(CamelCase.rename("RenameRule"), "renameRule");
        assert_eq!(SnakeCase.rename("RenameRule"), "rename_rule");
        assert_eq!(ScreamingSnakeCase.rename("rename_rule"), "RENAME_RULE");
        assert_eq!(KebabCase.rename("rename_rule"), "rename-rule");
        assert_eq!(ScreamingKebabCase.rename("rename_rule"), "RENAME-RULE");
    }
}