http_siren 0.1.0

Support for Siren responses in HTTP APIs
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
#![allow(clippy::needless_pass_by_value)]

use serde::Serialize;
use serde_json::Value;

/// Representation of a Siren document.
#[derive(Debug, Serialize)]
#[must_use]
pub struct Document<T>
where
    T: Serialize,
{
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub class:      Vec<String>,
    pub properties: T,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub entities:   Vec<Entity>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub links:      Vec<Link>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub actions:    Vec<Action>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title:      Option<String>,
}

/// Representation of an embedded entity. Either an embedded link or a full representation.
#[derive(Debug, Serialize)]
#[serde(untagged)]
#[must_use]
pub enum Entity {
    Link(Link),
    Representation(EmbeddedRepresentation),
}

/// Body of an embedded representation.
#[derive(Debug, Serialize)]
#[must_use]
pub struct EmbeddedRepresentation {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    rel:        Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    class:      Vec<String>,
    properties: Value,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    entities:   Vec<Entity>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    links:      Vec<Link>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    actions:    Vec<Action>,
    #[serde(skip_serializing_if = "Option::is_none")]
    title:      Option<String>,
}

/// Representation of a link. Either as a standard link or an embedded entity.
#[derive(Debug, Serialize)]
#[must_use]
pub struct Link {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub rel:        Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub class:      Vec<String>,
    pub href:       String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title:      Option<String>,
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,
}

/// Representation of an action.
#[derive(Debug, Serialize)]
#[must_use]
pub struct Action {
    pub name:       String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub class:      Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method:     Option<String>,
    pub href:       String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title:      Option<String>,
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub fields:     Vec<Field>,
}

/// Representation of a field within an action.
#[derive(Debug, Serialize)]
#[must_use]
pub struct Field {
    pub name:       String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub class:      Vec<String>,
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value:      Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title:      Option<String>,
}

impl<T> Document<T>
where
    T: Serialize,
{
    /// Create a new Document.
    ///
    /// # Parameters
    /// - `payload` - The payload of the document.
    pub fn new(payload: T) -> Self {
        Self {
            class:      vec![],
            properties: payload,
            entities:   vec![],
            links:      vec![],
            actions:    vec![],
            title:      None,
        }
    }

    /// Apply a lambda to specify additional details on the document.
    ///
    /// # Parameters
    /// - `f` - The lambda function to execute on the document.
    pub fn with<F>(self, f: F) -> Self
    where
        F: Fn(Self) -> Self,
    {
        f(self)
    }

    /// Specify a class for the document.
    ///
    /// # Parameters
    /// - `value` - The class to specify.
    pub fn with_class<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.class.push(value.to_string());

        self
    }

    /// Specify an embedded link for the document.
    ///
    /// # Parameters
    /// - `value` - The embedded link to specify.
    pub fn with_embedded_link<V>(mut self, value: V) -> Self
    where
        V: Into<Link>,
    {
        self.entities.push(Entity::Link(value.into()));

        self
    }

    /// Specify an embedded representation for the document.
    ///
    /// # Parameters
    /// - `value` - The embedded representation to specify.
    pub fn with_embedded_representation<V>(mut self, value: V) -> Self
    where
        V: Into<EmbeddedRepresentation>,
    {
        self.entities.push(Entity::Representation(value.into()));

        self
    }

    /// Specify a link for the document.
    ///
    /// # Parameters
    /// - `value` - The link to specify.
    pub fn with_link<L>(mut self, value: L) -> Self
    where
        L: Into<Link>,
    {
        self.links.push(value.into());

        self
    }

    /// Specify a action for the document.
    ///
    /// # Parameters
    /// - `value` - The action to specify.
    pub fn with_action<L>(mut self, value: L) -> Self
    where
        L: Into<Action>,
    {
        self.actions.push(value.into());

        self
    }

    /// Specify a title for the document.
    ///
    /// # Parameters
    /// - `value` - The title to specify.
    pub fn with_title<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.title = Some(value.to_string());

        self
    }
}

impl EmbeddedRepresentation {
    /// Create a new embedded representation.
    ///
    /// # Parameters
    /// - `payload` - The payload of the embedded representation.
    pub fn new<S>(payload: S) -> Self
    where
        S: Serialize,
    {
        let serialized = serde_json::to_value(payload).expect("Failed to serialize payload");

        Self {
            rel:        vec![],
            class:      vec![],
            properties: serialized,
            entities:   vec![],
            links:      vec![],
            actions:    vec![],
            title:      None,
        }
    }

    /// Apply a lambda to specify additional details on the representation.
    ///
    /// # Parameters
    /// - `f` - The lambda function to execute on the representation.
    pub fn with<F>(self, f: F) -> Self
    where
        F: Fn(Self) -> Self,
    {
        f(self)
    }

    /// Specify a link relation for the representation.
    ///
    /// # Parameters
    /// - `value` - The link relation to specify.
    pub fn with_rel<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.rel.push(value.to_string());

        self
    }

    /// Specify a class for the representation.
    ///
    /// # Parameters
    /// - `value` - The class to specify.
    pub fn with_class<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.class.push(value.to_string());

        self
    }

    /// Specify an embedded link for the representation.
    ///
    /// # Parameters
    /// - `value` - The embedded link to specify.
    pub fn with_embedded_link<V>(mut self, value: V) -> Self
    where
        V: Into<Link>,
    {
        self.entities.push(Entity::Link(value.into()));

        self
    }

    /// Specify an embedded representation for the representation.
    ///
    /// # Parameters
    /// - `value` - The embedded representation to specify.
    pub fn with_embedded_representation<V>(mut self, value: V) -> Self
    where
        V: Into<EmbeddedRepresentation>,
    {
        self.entities.push(Entity::Representation(value.into()));

        self
    }

    /// Specify a link for the representation.
    ///
    /// # Parameters
    /// - `value` - The link to specify.
    pub fn with_link<L>(mut self, value: L) -> Self
    where
        L: Into<Link>,
    {
        self.links.push(value.into());

        self
    }

    /// Specify an action for the representation.
    ///
    /// # Parameters
    /// - `value` - The action to specify.
    pub fn with_action<L>(mut self, value: L) -> Self
    where
        L: Into<Action>,
    {
        self.actions.push(value.into());

        self
    }

    /// Specify a title for the representation.
    ///
    /// # Parameters
    /// - `value` - The title to specify.
    pub fn with_title<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.title = Some(value.to_string());

        self
    }
}

impl Link {
    /// Create a new link.
    ///
    /// # Parameters
    /// - `href` - The href for the link.
    pub fn new<S>(href: S) -> Self
    where
        S: ToString,
    {
        Self {
            rel:        vec![],
            class:      vec![],
            href:       href.to_string(),
            title:      None,
            media_type: None,
        }
    }

    /// Apply a lambda to specify additional details on the link.
    ///
    /// # Parameters
    /// - `f` - The lambda function to execute on the link.
    pub fn with<F>(self, f: F) -> Self
    where
        F: Fn(Self) -> Self,
    {
        f(self)
    }

    /// Specify a class for the link.
    ///
    /// # Parameters
    /// - `value` - The class to specify.
    pub fn with_class<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.class.push(value.to_string());

        self
    }

    /// Specify a link relation for the link.
    ///
    /// # Parameters
    /// - `value` - The link relation to specify.
    pub fn with_rel<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.rel.push(value.to_string());

        self
    }

    /// Specify a type for the link.
    ///
    /// # Parameters
    /// - `value` - The type to specify.
    pub fn with_type<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.media_type = Some(value.to_string());

        self
    }

    /// Specify a title for the link.
    ///
    /// # Parameters
    /// - `value` - The title to specify.
    pub fn with_title<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.title = Some(value.to_string());

        self
    }
}

impl Action {
    /// Create a new action.
    ///
    /// # Parameters
    /// - `name` - The name of the action.
    /// - `href` - The href for the action.
    pub fn new<N, H>(name: N, href: H) -> Self
    where
        N: ToString,
        H: ToString,
    {
        Self {
            name:       name.to_string(),
            class:      vec![],
            method:     None,
            href:       href.to_string(),
            title:      None,
            media_type: None,
            fields:     vec![],
        }
    }

    /// Apply a lambda to specify additional details on the action.
    ///
    /// # Parameters
    /// - `f` - The lambda function to execute on the action.
    pub fn with<F>(self, f: F) -> Self
    where
        F: Fn(Self) -> Self,
    {
        f(self)
    }

    /// Specify a class for the action.
    ///
    /// # Parameters
    /// - `value` - The class to specify.
    pub fn with_class<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.class.push(value.to_string());

        self
    }

    /// Specify a type for the action.
    ///
    /// # Parameters
    /// - `value` - The type to specify.
    pub fn with_type<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.media_type = Some(value.to_string());

        self
    }

    /// Specify a title for the action.
    ///
    /// # Parameters
    /// - `value` - The title to specify.
    pub fn with_title<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.title = Some(value.to_string());

        self
    }

    /// Specify an HTTP method for the action.
    ///
    /// # Parameters
    /// - `value` - The HTTP method to specify.
    pub fn with_method<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.method = Some(value.to_string());

        self
    }

    /// Specify a field for the action.
    ///
    /// # Parameters
    /// - `value` - The field to specify.
    pub fn with_field<V>(mut self, value: V) -> Self
    where
        V: Into<Field>,
    {
        self.fields.push(value.into());

        self
    }
}

impl Field {
    /// Create a new field.
    ///
    /// # Parameters
    /// - `name` - The name of the field.
    pub fn new<S>(name: S) -> Self
    where
        S: ToString,
    {
        Self {
            name:       name.to_string(),
            class:      vec![],
            input_type: None,
            value:      None,
            title:      None,
        }
    }

    /// Apply a lambda to specify additional details on the field.
    ///
    /// # Parameters
    /// - `f` - The lambda function to execute on the field.
    pub fn with<F>(self, f: F) -> Self
    where
        F: Fn(Self) -> Self,
    {
        f(self)
    }

    /// Specify a class for the field.
    ///
    /// # Parameters
    /// - `value` - The class to specify.
    pub fn with_class<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.class.push(value.to_string());

        self
    }

    /// Specify a type for the field.
    ///
    /// # Parameters
    /// - `value` - The type to specify.
    pub fn with_type<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.input_type = Some(value.to_string());

        self
    }

    /// Specify a value for the field.
    ///
    /// # Parameters
    /// - `value` - The value to specify.
    pub fn with_value<S>(mut self, value: S) -> Self
    where
        S: Serialize,
    {
        let serialized = serde_json::to_value(value).expect("Failed to serialize value");

        self.value = Some(serialized);

        self
    }

    /// Specify a title for the field.
    ///
    /// # Parameters
    /// - `value` - The title to specify.
    pub fn with_title<S>(mut self, value: S) -> Self
    where
        S: ToString,
    {
        self.title = Some(value.to_string());

        self
    }
}

#[cfg(test)]
mod tests {
    use assert2::check;
    use serde_json::json;

    use super::{
        super::values::{FieldTypes, HttpMethods, LinkRelation},
        *,
    };

    #[test]
    fn test_example() {
        let document = Document::new(json!({
            "orderNumber": 42,
            "itemCount": 3,
            "status": "pending"
        }))
        .with_class("order")
        .with_embedded_link(
            Link::new("http://api.x.io/orders/42/items")
                .with_class("items")
                .with_class("collection")
                .with_rel("http://x.io/rels/order-items"),
        )
        .with_embedded_representation(
            EmbeddedRepresentation::new(json!({
                "customerId": "pj123",
                "name": "Peter Joseph"
            }))
            .with_class("info")
            .with_class("customer")
            .with_rel("http://x.io/rels/customer")
            .with_link(
                Link::new("http://api.x.io/customers/pj123").with_rel(LinkRelation::SelfLink),
            ),
        )
        .with_action(
            Action::new("add-item", "http://api.x.io/orders/42/items")
                .with_title("Add Item")
                .with_method(HttpMethods::POST)
                .with_type("application/x-www-form-urlencoded")
                .with_field(
                    Field::new("orderNumber")
                        .with_type(FieldTypes::Hidden)
                        .with_value("42"),
                )
                .with_field(Field::new("productCode").with_type(FieldTypes::Text))
                .with_field(Field::new("quantity").with_type(FieldTypes::Number)),
        )
        .with_link(Link::new("http://api.x.io/orders/42").with_rel(LinkRelation::SelfLink))
        .with_link(Link::new("http://api.x.io/orders/41").with_rel(LinkRelation::Previous))
        .with_link(Link::new("http://api.x.io/orders/43").with_rel(LinkRelation::Next));

        let serialized = serde_json::to_value(document).unwrap();

        check!(
            serialized
                == json!(
                {
                  "class": [
                    "order"
                  ],
                  "properties": {
                    "orderNumber": 42,
                    "itemCount": 3,
                    "status": "pending"
                  },
                  "entities": [
                    {
                      "rel": [
                        "http://x.io/rels/order-items"
                      ],
                      "class": [
                        "items",
                        "collection"
                      ],
                      "href": "http://api.x.io/orders/42/items"
                    },
                    {
                      "rel": [
                        "http://x.io/rels/customer"
                      ],
                      "class": [
                        "info",
                        "customer"
                      ],
                      "properties": {
                        "customerId": "pj123",
                        "name": "Peter Joseph"
                      },
                      "links": [
                        {
                          "rel": [
                            "self"
                          ],
                          "href": "http://api.x.io/customers/pj123"
                        }
                      ]
                    }
                  ],
                  "links": [
                    {
                      "rel": [
                        "self"
                      ],
                      "href": "http://api.x.io/orders/42"
                    },
                    {
                      "rel": [
                        "previous"
                      ],
                      "href": "http://api.x.io/orders/41"
                    },
                    {
                      "rel": [
                        "next"
                      ],
                      "href": "http://api.x.io/orders/43"
                    }
                  ],
                  "actions": [
                    {
                      "name": "add-item",
                      "method": "POST",
                      "href": "http://api.x.io/orders/42/items",
                      "title": "Add Item",
                      "type": "application/x-www-form-urlencoded",
                      "fields": [
                        {
                          "name": "orderNumber",
                          "type": "hidden",
                          "value": "42"
                        },
                        {
                          "name": "productCode",
                          "type": "text"
                        },
                        {
                          "name": "quantity",
                          "type": "number"
                        }
                      ]
                    }
                  ]
                })
        );
    }
}