proteus 0.5.0

Proteus is intended to make dynamic transformation of data using serde serializable, deserialize using JSON and a JSON transformation syntax similar to Javascript JSON syntax. It also supports registering custom Actions to be used in the syntax.
Documentation
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! builder and finalized transformer representations..

use crate::action::Action;
use crate::errors::Error;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::borrow::Cow;

/// This type provides the ability to create a [Transformer](struct.Transformer.html) for use.
#[derive(Debug)]
pub struct TransformBuilder {
    actions: Vec<Box<dyn Action>>,
}

impl Default for TransformBuilder {
    fn default() -> Self {
        TransformBuilder {
            actions: Vec::new(),
        }
    }
}

impl TransformBuilder {
    /// adds a single [Action](action/trait.Action.html) to be applied during the transformation.
    pub fn add_action(mut self, action: Box<dyn Action>) -> Self {
        self.actions.push(action);
        self
    }

    /// adds multiple [Action](action/trait.Action.html) to be applied during the transformation.
    pub fn add_actions(mut self, mut actions: Vec<Box<dyn Action>>) -> Self {
        self.actions.append(&mut actions);
        self
    }

    /// creates the final [Transformer](struct.Transformer.html) representation.
    pub fn build(self) -> Result<Transformer, Error> {
        // Error return value is reserved for future optimization during the build phase.
        Ok(Transformer {
            actions: self.actions,
        })
    }
}

/// This type represents a realized transformation which can be used on data.
#[derive(Debug, Serialize, Deserialize)]
pub struct Transformer {
    actions: Vec<Box<dyn Action>>,
}

impl Transformer {
    /// directly applies the transform actions, in order, on the source and sets directly on the
    /// provided destination.
    ///
    /// The destination in question can be an existing Object and the data set on it at any level.
    #[inline]
    pub fn apply_to_destination(
        &self,
        source: &Value,
        destination: &mut Value,
    ) -> Result<(), Error> {
        for a in self.actions.iter() {
            a.apply(source, destination)?;
        }
        Ok(())
    }

    /// applies the transform actions, in order, on the source and returns a final Value.
    #[inline]
    pub fn apply(&self, source: &Value) -> Result<Value, Error> {
        let mut value = Value::Null;
        self.apply_to_destination(source, &mut value)?;
        Ok(value)
    }

    /// applies the transform actions, in order, on the source slice.
    ///
    /// The source string MUST be valid utf-8 JSON.
    #[inline]
    pub fn apply_from_slice(&self, source: &[u8]) -> Result<Value, Error> {
        self.apply(&serde_json::from_slice(source)?)
    }

    /// applies the transform actions, in order, on the source string.
    ///
    /// The source string MUST be valid JSON.
    #[inline]
    pub fn apply_from_str<'a, S>(&self, source: S) -> Result<Value, Error>
    where
        S: Into<Cow<'a, str>>,
    {
        self.apply(&serde_json::from_str(&source.into())?)
    }

    /// applies the transform actions, in order, on the source string and returns the type
    /// represented by D.
    ///
    /// The source string MUST be valid JSON.
    #[inline]
    pub fn apply_from_str_to<'a, S, D>(&self, source: S) -> Result<D, Error>
    where
        S: Into<Cow<'a, str>>,
        D: DeserializeOwned,
    {
        let value = self.apply(&serde_json::from_str(&source.into())?)?;
        Ok(serde_json::from_value::<D>(value)?)
    }

    /// applies the transform actions, in order, on the serializable source and returns the type
    /// represented by D.
    #[inline]
    pub fn apply_to<S, D>(&self, source: S) -> Result<D, Error>
    where
        S: Serialize,
        D: DeserializeOwned,
    {
        let value = self.apply(&serde_json::to_value(source)?)?;
        Ok(serde_json::from_value::<D>(value)?)
    }
}

#[cfg(test)]
mod tests {
    use crate::{Parsable, Parser, TransformBuilder};
    use serde_json::{json, Value};

    #[test]
    fn constant() -> Result<(), Box<dyn std::error::Error>> {
        let action = Parser::parse(r#"const("Dean Karn")"#, "full_name")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let destination = trans.apply(&source)?;
        let expected = json!({"full_name":"Dean Karn"});
        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn array_of_array_to_array() -> Result<(), Box<dyn std::error::Error>> {
        let action = Parser::parse(r#"const("Dean Karn")"#, "[2][1]")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let destination = trans.apply(&source)?;
        assert!(destination.is_array());

        let expected = json!([null, null, [null, "Dean Karn"]]);

        assert_eq!(expected, destination);

        let action = Parser::parse(r#"const("Dean Karn")"#, "[2][1].name")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let destination = trans.apply(&source)?;
        assert!(destination.is_array());

        let expected = json!([null, null, [null, {"name":"Dean Karn"}]]);
        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn push_array() -> Result<(), Box<dyn std::error::Error>> {
        let action = Parser::parse(r#"const("Dean Karn")"#, "[2][]")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let destination = trans.apply(&source)?;
        assert!(destination.is_array());

        let expected = json!([null, null, ["Dean Karn"]]);

        assert_eq!(expected, destination);

        let action = Parser::parse(r#"const("Dean Karn")"#, "[2][]")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let mut destination = json!([null, null, [null]]);

        let res = trans.apply_to_destination(&source, &mut destination);
        assert!(!res.is_err());
        assert!(destination.is_array());

        let expected = json!([null, null, [null, "Dean Karn"]]);

        assert_eq!(expected, destination);

        let action = Parser::parse(r#"const("Dean Karn")"#, "[2]")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let destination = trans.apply(&source)?;
        assert!(destination.is_array());

        let expected = json!([null, null, "Dean Karn"]);

        assert_eq!(expected, destination);

        // testing replace
        let action = Parser::parse(r#"const("Dean Karn")"#, "[2]")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let mut destination = json!([null, null, {"id":"id"}]);
        let res = trans.apply_to_destination(&source, &mut destination);
        assert!(!res.is_err());
        assert!(destination.is_array());

        let expected = json!([null, null, "Dean Karn"]);

        assert_eq!(expected, destination);

        let action = Parser::parse(r#"const("Dean Karn")"#, "[1].key.key2")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let destination = trans.apply(&source)?;
        assert!(destination.is_array());

        let expected = json!([null, {"key": {"key2":"Dean Karn"}}]);

        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn append_array_top_level() -> Result<(), Box<dyn std::error::Error>> {
        let action = Parser::parse(r#"const([null,"Dean Karn"])"#, "[]")?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = "".into();
        let mut destination = Value::Array(vec!["test".into()]);
        let res = trans.apply_to_destination(&source, &mut destination);
        assert!(!res.is_err());
        assert!(destination.is_array());

        let expected = json!(["test", [null, "Dean Karn"]]);

        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn test_top_level() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("existing_key", "rename_from_existing_key"),
            Parsable::new("my_array[0]", "used_to_be_array"),
            Parsable::new(r#"const("consant_value")"#, "const"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let input = json!({
            "existing_key":"my_val1",
            "my_array":["idx_0_value"]
        });
        let expected = json!({"const":"consant_value","rename_from_existing_key":"my_val1","used_to_be_array":"idx_0_value"});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);
        Ok(())
    }

    #[test]
    fn test_10_top_level() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("top1", "new1"),
            Parsable::new("top2", "new2"),
            Parsable::new("top3", "new3"),
            Parsable::new("top4", "new4"),
            Parsable::new("top5", "new5"),
            Parsable::new("top6", "new6"),
            Parsable::new("top7", "new7"),
            Parsable::new("top8", "new8"),
            Parsable::new("top9", "new9"),
            Parsable::new("top10", "new10"),
        ])?;

        let trans = TransformBuilder::default().add_actions(actions).build()?;

        let input = json!({
            "top1": "value",
            "top2": "value",
            "top3": "value",
            "top4": "value",
            "top5": "value",
            "top6": "value",
            "top7": "value",
            "top8": "value",
            "top9": "value",
            "top10": "value"
        });
        let expected = json!({"new1":"value","new10":"value","new2":"value","new3":"value","new4":"value","new5":"value","new6":"value","new7":"value","new8":"value","new9":"value"});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);
        Ok(())
    }

    #[test]
    fn test_join() -> Result<(), Box<dyn std::error::Error>> {
        let action = Parser::parse(
            r#"join(" ", const("Mr."), first_name, meta.middle_name, last_name)"#,
            "full_name",
        )?;
        let trans = TransformBuilder::default().add_action(action).build()?;

        let input = json!({
            "first_name": "Dean",
            "last_name": "Karn",
            "meta": {
                "middle_name":"Peter"
            }
        });
        let expected = json!({"full_name":"Mr. Dean Peter Karn"});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);
        Ok(())
    }

    #[test]
    fn test_explicit_key() -> Result<(), Box<dyn std::error::Error>> {
        let action = Parser::parse(r#"["name(1)"]"#, r#"["my name is ([2][])"]"#)?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = json!({"name(1)":"Dean Karn"});
        let destination = trans.apply(&source)?;
        assert!(destination.is_object());

        let expected = json!({"my name is ([2][])": "Dean Karn"});

        assert_eq!(expected, destination);

        let action = Parser::parse(r#"["name(1)"].name"#, r#"["my name is ([2][])"]"#)?;
        let trans = TransformBuilder::default().add_action(action).build()?;
        let source = json!({"name(1)":{"name":"Dean Karn"}});
        let destination = trans.apply(&source)?;
        assert!(destination.is_object());

        let expected = json!({"my name is ([2][])": "Dean Karn"});
        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn merge_object() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "person.full_name"),
            Parsable::new("person.metadata", "person{}"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let source = json!({"person":{"name":"Dean Karn", "metadata":{"age":1}}});
        let destination = trans.apply(&source)?;
        let expected = json!({"person":{"full_name":"Dean Karn", "age":1}});
        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn combine_array() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "person[0]"),
            Parsable::new("person.metadata", "person[+]"), // CombineArray = [+], MergeArray = [-]
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let source = json!({"person":{"name":"Dean Karn", "metadata":[1]}});
        let destination = trans.apply(&source)?;
        let expected = json!({"person":["Dean Karn", 1]});
        assert_eq!(expected, destination);

        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "[0]"),
            Parsable::new("person.metadata", "[+]"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let source = json!({"person":{"name":"Dean Karn", "metadata":[1]}});
        let mut destination = Value::Array(vec![1.into()]);
        let _ = trans.apply_to_destination(&source, &mut destination);
        let expected = json!(["Dean Karn", 1]);
        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn replace_array() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "person[0]"),
            Parsable::new("person.metadata", "person[0]"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let source = json!({"person":{"name":"Dean Karn", "metadata":[1]}});
        let destination = trans.apply(&source)?;
        let expected = json!({"person":[[1]]});
        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn merge_array() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "person[0]"),
            Parsable::new("person.metadata", "person[-]"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let source = json!({"person":{"name":"Dean Karn", "metadata":[1]}});
        let destination = trans.apply(&source)?;
        let expected = json!({"person":[1]});
        assert_eq!(expected, destination);

        // test source len > existing
        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "person[0]"),
            Parsable::new("person.metadata", "person[-]"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let source = json!({"person":{"name":"Dean Karn", "metadata":[1, "blah", 45.6]}});
        let destination = trans.apply(&source)?;
        let expected = json!({"person":[1,"blah",45.6]});
        assert_eq!(expected, destination);

        // test source len < existing
        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "person[5]"),
            Parsable::new("person.metadata", "person[-]"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let source = json!({"person":{"name":"Dean Karn", "metadata":[1, "blah", 45.6]}});
        let destination = trans.apply(&source)?;
        let expected = json!({"person":[1, "blah", 45.6, null, null, "Dean Karn"]});
        assert_eq!(expected, destination);
        Ok(())
    }

    #[test]
    fn transformer_serialization() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("person.name", "person[0]"),
            Parsable::new("person.metadata", "person[0]"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let res = serde_json::to_string(&trans)?;
        assert_eq!(res, "{\"actions\":[{\"type\":\"Setter\",\"namespace\":[{\"Object\":{\"id\":\"person\"}},{\"Array\":{\"index\":0}}],\"child\":{\"type\":\"Getter\",\"namespace\":[{\"Object\":{\"id\":\"person\"}},{\"Object\":{\"id\":\"name\"}}]}},{\"type\":\"Setter\",\"namespace\":[{\"Object\":{\"id\":\"person\"}},{\"Array\":{\"index\":0}}],\"child\":{\"type\":\"Getter\",\"namespace\":[{\"Object\":{\"id\":\"person\"}},{\"Object\":{\"id\":\"metadata\"}}]}}]}");
        Ok(())
    }

    #[test]
    fn test_set_and_get_top_level() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[Parsable::new("", "")])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;
        let input = json!({
            "existing_key":"my_val1",
            "my_array":["idx_0_value"]
        });
        let expected = json!({"existing_key":"my_val1","my_array":["idx_0_value"]});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);
        Ok(())
    }

    #[test]
    fn test_sum() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new(r#"sum(const(1.1), arr, len(obj))"#, "sum"),
            Parsable::new("sum(len(arr))", "sum2"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;

        let input = json!({
            "arr": [1, 2, 3],
            "obj": {"key":"value"}
        });
        let expected = json!({"sum":8.1, "sum2": 3});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);

        let actions = Parser::parse_multi(&[Parsable::new("sum()", "sum")])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;

        let input = json!([1, 2, 3]);
        let expected = json!({"sum":6});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);

        Ok(())
    }

    #[test]
    fn test_len() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("len()", "len1"),
            Parsable::new("len(arr)", "len2"),
            Parsable::new("len(obj)", "len3"),
            Parsable::new("len(obj.key)", "len4"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;

        let input = json!({
            "arr": [1, 2, 3],
            "obj": {"key":"value"}
        });
        let expected = json!({"len1": 2, "len2": 3, "len3": 1, "len4": 5});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);
        Ok(())
    }

    #[test]
    fn test_trim() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new("trim(key)", "res1"),
            Parsable::new("trim_start(key)", "res2"),
            Parsable::new("trim_end(key)", "res3"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;

        let input = json!({"key": " value "});
        let expected = json!({"res1": "value", "res2": "value ", "res3": " value"});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);
        Ok(())
    }

    #[test]
    fn test_strip() -> Result<(), Box<dyn std::error::Error>> {
        let actions = Parser::parse_multi(&[
            Parsable::new(r#"strip_prefix("v", key)"#, "res1"),
            Parsable::new(r#"strip_suffix("e", key)"#, "res2"),
        ])?;
        let trans = TransformBuilder::default().add_actions(actions).build()?;

        let input = json!({"key": "value"});
        let expected = json!({"res1": "alue", "res2": "valu"});
        let output = trans.apply(&input)?;
        assert_eq!(expected, output);
        Ok(())
    }
}