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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
use failure::Error;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::ServerInfo;
use df_st_core::SchemaExample;
use rocket::request::{FromQuery, Query};
use rocket::State;
use rocket_okapi::{
    gen::OpenApiGenerator, request::get_nested_query_parameters, request::OpenApiFromQuery,
};
use std::cmp;
use std::fmt;

/// This trait allows the item to be used as a response.
/// Allows the item to be nested in an `ApiPage` or `ApiItem`.
pub trait ApiObject {
    /// A unique name for the type. All in `snake_case` and singular.
    fn get_type() -> String;
    /// The URL to an item in the api.
    fn get_item_link(&self, base_url: &str) -> String;
    /// The URL to a page (list) in the api.
    /// This URL will be extended with query parameters.
    fn get_page_link(base_url: &str) -> String;
    /// The URL to the count page in the api.
    /// This URL will be extended with query parameters.
    fn get_count_link(base_url: &str) -> String;
}

/// A paged response from the API.
/// The actual requested data can be found in the `data` object.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
#[schemars(example = "Self::example")]
pub struct ApiPage<D>
where
    D: ApiObject + Serialize + SchemaExample,
{
    /// The maximum amount of items in this response.
    pub max_page_size: u32,
    /// The total amount of items. (across all pages)
    /// Note: id's usually start at 0 so if there are 10 total items the list id is 9.
    /// But id's can be missing so do not use this to calculate id's!
    pub total_item_count: u32,
    /// The offset from the start of the database structure.
    /// This value takes the sorting of the page into account.
    pub page_start: u32,
    /// The actual size of the response. (page_size<=max_page_size).
    pub page_size: u32,
    /// The number of the page.
    /// This value is `page_nr = page_start/max_page_size`
    pub page_nr: u32,
    /// Order of the page. "asc" = A-Z, "desc" = Z-A.
    /// This field is only present if an order is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<OrderTypes>,
    /// Name of the field for what it is ordered by.
    /// This field is only present if an order_by is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_by: Option<String>,
    /// Tag to identify this version of the page.
    /// [More info here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag).
    /// This tag can be used to improve caching.
    /// ETag is a Sha256 of the whole response
    /// (including links and other metadata, excluding the etag itself.).
    pub etag: String,
    /// Links the various related items.
    pub links: ApiPageLinks,
    /// List of actual requested data.
    pub data: Vec<ApiItem<D>>,
    /// The etag given in the request.
    #[serde(skip)]
    pub given_etag: String,
    /// Server base url.
    /// Not included in response.
    #[serde(skip)]
    pub base_url: String,
    /// Maximum amount of items requested on a page.
    /// Set by server at startup, see config.
    /// Not included in response.
    #[serde(skip)]
    pub server_max_page_size: u32,
}

impl<D> SchemaExample for ApiPage<D>
where
    D: SchemaExample + Serialize + ApiObject,
{
    fn example() -> Self {
        let link = D::get_page_link(&"http://127.0.0.1:20350/api".to_owned());
        Self {
            max_page_size: 100,
            total_item_count: 2731,
            page_start: 300,
            page_size: 100,
            page_nr: 3,
            order: Some(OrderTypes::Asc),
            order_by: Some("type".to_owned()),
            etag: "19fb53cca19546fd3eac64e11cc5a24a965dbe426fb932fcfc324569a6cc21a6".to_owned(),
            links: ApiPageLinks {
                self_: format!("{}?per_page=100&order=asc&order_by=type&page=3", link),
                first: Some(format!(
                    "{}?per_page=100&order=asc&order_by=type&page=0",
                    link
                )),
                prev: Some(format!(
                    "{}?per_page=100&order=asc&order_by=type&page=2",
                    link
                )),
                next: Some(format!(
                    "{}?per_page=100&order=asc&order_by=type&page=4",
                    link
                )),
                last: Some(format!(
                    "{}?per_page=100&order=asc&order_by=type&page=27",
                    link
                )),
            },
            data: vec![ApiItem::<D>::example()],

            given_etag: "".to_owned(),
            base_url: "".to_owned(),
            server_max_page_size: 0,
        }
    }
}

impl<D> ApiPage<D>
where
    D: ApiObject + Default + Serialize + SchemaExample,
{
    pub fn new(pagination: &ApiPagination, server_info: &State<ServerInfo>) -> Self {
        let server_info = server_info.inner().clone();
        let mut new_object = Self::default();
        new_object.base_url = server_info.base_url.clone();
        new_object.order = pagination.order.clone();
        new_object.order_by = pagination.order_by.clone();
        new_object.server_max_page_size = server_info.page_max_limit;
        new_object.max_page_size = server_info.default_max_page_size;
        if let Some(per_page) = pagination.per_page {
            // Make sure to not go over `page_max_limit`
            new_object.max_page_size = cmp::min(per_page, server_info.page_max_limit);
        }
        // make sure it is at least 1 (>=1)
        new_object.max_page_size = cmp::max(new_object.max_page_size, 1);
        if let Some(page) = pagination.page {
            new_object.page_start = page * new_object.max_page_size;
        }
        if let Some(etag) = &pagination.etag {
            new_object.given_etag = etag.clone();
        }

        new_object
    }

    fn set_links(&mut self) {
        let mut query_parameters = Vec::new();
        let qp_page = if self.page_start != 0 {
            format!("page={}", self.page_nr)
        } else {
            "".to_owned()
        };

        if self.max_page_size != self.server_max_page_size {
            query_parameters.push(format!("per_page={}", self.max_page_size));
        }

        if let Some(order) = &self.order {
            query_parameters.push(format!("order={}", order));
        }

        if let Some(order_by) = &self.order_by {
            query_parameters.push(format!("order_by={}", order_by));
        }

        // Self
        let mut links = ApiPageLinks::default();
        let base_api_path = D::get_page_link(&self.base_url);
        if qp_page.is_empty() {
            links.self_ = format!("{}?{}", base_api_path, query_parameters.join("&"));
        } else {
            let mut local_qp = query_parameters.clone();
            local_qp.push(qp_page);
            links.self_ = format!("{}?{}", base_api_path, local_qp.join("&"));
        }
        // First
        if self.page_start >= 1 {
            let mut local_qp = query_parameters.clone();
            local_qp.push("page=0".to_owned());
            links.first = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        // Prev
        if self.page_start >= 1 {
            let mut local_qp = query_parameters.clone();
            local_qp.push(format!("page={}", self.page_nr - 1));
            links.prev = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        // Next
        if self.page_start + self.max_page_size < self.total_item_count {
            let mut local_qp = query_parameters.clone();
            local_qp.push(format!("page={}", self.page_nr + 1));
            links.next = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        // Last
        if self.page_start + self.max_page_size < self.total_item_count {
            let mut local_qp = query_parameters;
            local_qp.push(format!(
                "page={}",
                (self.total_item_count - 1) / self.max_page_size
            ));
            links.last = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        self.links = links;
    }

    /// Store the data in the object and construct links and calculate ETag.
    /// Return if true etag match with request tag.
    pub fn wrap(&mut self, list: Vec<D>) -> bool {
        self.data = self.warp_data_list(list);
        self.page_nr = self.page_start / self.max_page_size;
        self.set_links();
        self.set_etag()
    }

    /// Hash the data using Sha256 to create the ETag.
    /// After this function is called no extra data should be added.
    /// (or it should be rehashed).
    fn set_etag(&mut self) -> bool {
        // If Sha256 is no longer strong enough or is broken it should and can be easily
        // replaced in this function.
        use sha2::{Digest, Sha256};
        // Reset any already set ETag (so this does not effect the hash)
        self.etag = "".to_owned();
        // Hash the data to create the etag.
        let mut hasher = Sha256::new();
        // Convert data to json string.
        // Conversion is done to eliminate non-public values to effect the hash.
        let json_data = serde_json::to_string(self).unwrap();
        hasher.update(json_data);
        // Convert to `String` and store result in etag
        self.etag = format!("{:x}", hasher.finalize());
        // Check if ETags match
        self.etag == self.given_etag
    }

    fn warp_data_list(&mut self, list: Vec<D>) -> Vec<ApiItem<D>> {
        let mut data = Vec::new();
        self.page_size = list.len() as u32;

        for item in list {
            data.push(ApiItem::wrap_new(item, &self.base_url));
        }

        data
    }

    /// Returns if the page should be sorted and in what order.
    pub fn get_db_order(&self) -> Option<df_st_db::OrderTypes> {
        match &self.order {
            Some(x) => Some(match x {
                OrderTypes::Asc => df_st_db::OrderTypes::Asc,
                OrderTypes::Desc => df_st_db::OrderTypes::Desc,
            }),
            None => None,
        }
    }
}

/// A list of links to easily enable navigation in paging.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
#[schemars(example = "Self::example")]
pub struct ApiPageLinks {
    /// Link to this page itself. Can be used to refresh the data.
    #[serde(rename = "self")]
    pub self_: String,
    /// Link to the first page in the order.
    /// If `None` you are on the first page.
    /// Note: This can be the same link as `prev`.
    pub first: Option<String>,
    /// Link to the previous page in the order.
    /// If `None` there is no previous page.
    pub prev: Option<String>,
    /// Link to the next page in the order.
    /// If `None` there is no next page.
    pub next: Option<String>,
    /// Link to the last page in the order.
    /// If `None` you are on the last page.
    /// Note: This can be the same link as `next`.
    pub last: Option<String>,
}

impl SchemaExample for ApiPageLinks {
    fn example() -> Self {
        Self {
            self_:
                "http://127.0.0.1:20350/api/examples?per_page=100&order=asc&order_by=type&page=3"
                    .to_owned(),
            first: Some(
                "http:///127.0.0.1:20350/api/examples?per_page=100&order=asc&order_by=type&page=0"
                    .to_owned(),
            ),
            prev: Some(
                "http:///127.0.0.1:20350/api/examples?per_page=100&order=asc&order_by=type&page=2"
                    .to_owned(),
            ),
            next: Some(
                "http:///127.0.0.1:20350/api/examples?per_page=100&order=asc&order_by=type&page=4"
                    .to_owned(),
            ),
            last: Some(
                "http:///127.0.0.1:20350/api/examples?per_page=100&order=asc&order_by=type&page=27"
                    .to_owned(),
            ),
        }
    }
}

/// A Wrapper for an `ApiObject` that includes additional metadata.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
#[schemars(example = "Self::example")]
pub struct ApiItem<D>
where
    D: ApiObject + Serialize + SchemaExample,
{
    /// A unique string identifier for this type.
    #[serde(rename = "_type")]
    pub type_: String,
    /// Links the various related items.
    #[serde(rename = "_links")]
    pub links: ApiItemLinks,
    /// The included data item.
    #[serde(flatten)]
    pub data: D,
    /// Server base url.
    /// Not included in response.
    #[serde(skip)]
    pub base_url: String,
}

impl<D> SchemaExample for ApiItem<D>
where
    D: SchemaExample + Serialize + ApiObject,
{
    fn example() -> Self {
        Self {
            type_: D::get_type(),
            links: ApiItemLinks {
                self_: Some(D::example().get_item_link(&"http://127.0.0.1:20350/api".to_owned())),
            },
            data: D::example(),
            base_url: "".to_owned(),
        }
    }
}

impl<D> ApiItem<D>
where
    D: ApiObject + Default + Serialize + SchemaExample,
{
    pub fn new(server_info: &State<ServerInfo>) -> Self {
        let server_info = server_info.inner().clone();
        let mut new_object = Self::default();
        new_object.base_url = server_info.base_url;
        new_object
    }

    /// Store the data in the object and construct links.
    pub fn wrap(&mut self, item: D) {
        let link = item.get_item_link(&self.base_url);
        self.data = item;
        self.type_ = D::get_type();
        self.links = ApiItemLinks { self_: Some(link) };
    }

    /// Create and wrap the item.
    /// This is the same as doing:
    /// ```ignore
    /// let api_item = ApiItem::wrap_new(result_item, &server_info.base_url);
    /// // same as:
    /// let api_item = ApiItem::new(server_info);
    /// api_item.wrap(result_item);
    /// ```
    pub fn wrap_new(item: D, base_url: &str) -> ApiItem<D> {
        let mut return_object = ApiItem::default();
        return_object.base_url = base_url.to_string();
        return_object.wrap(item);
        return_object
    }
}

/// Links related to a specific `ApiObject`.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
#[schemars(example = "Self::example")]
pub struct ApiItemLinks {
    /// The url to request this individual item.
    #[serde(rename = "self")]
    pub self_: Option<String>,
}

impl SchemaExample for ApiItemLinks {
    fn example() -> Self {
        Self {
            self_: Some("http://127.0.0.1:20350/api/examples/5".to_owned()),
        }
    }
}

/// A paged response from the API.
/// The actual requested data can be found in the `data` object.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
#[schemars(example = "Self::example")]
pub struct ApiCountPage<C, D>
where
    C: ApiObject + Serialize + SchemaExample,
    D: ApiObject + Serialize + SchemaExample,
{
    /// The maximum amount if items in this response.
    pub max_page_size: u32,
    /// The total amount of items. (across all pages)
    /// Note: id's usually start at 0 so if there are 10 total items the list id is 9.
    /// But id's can be missing so do not use this to calculate id's!
    pub total_item_count: u32,
    /// The offset from the start of the database structure.
    /// This value takes the sorting of the page into account.
    pub page_start: u32,
    /// The actual size of the response. (page_size<=max_page_size).
    pub page_size: u32,
    /// The number of the page.
    /// This value is `page_nr = page_start/max_page_size`
    pub page_nr: u32,
    /// Name of the field it is grouped by.
    pub group_by: Option<String>,
    /// Tag to identify this version of the page.
    /// [More info here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag).
    /// This tag can be used to improve caching.
    /// ETag is a Sha256 of the whole response
    /// (including links and other metadata, excluding the etag itself.).
    pub etag: String,
    /// Links the various related items.
    pub links: ApiPageLinks,
    /// List of actual requested data.
    pub data: Vec<ApiMinimalItem<C>>,
    /// The etag given in the request.
    #[serde(skip)]
    pub given_etag: String,
    /// Server base url.
    /// Not included in response.
    #[serde(skip)]
    pub base_url: String,
    /// Maximum amount of items requested on a page.
    /// Set by server at startup, see config.
    /// Not included in response.
    #[serde(skip)]
    pub server_max_page_size: u32,
    /// Not used, but used to create dynamic links
    #[serde(skip)]
    parent_object: D,
}

impl<C, D> SchemaExample for ApiCountPage<C, D>
where
    C: SchemaExample + Serialize + ApiObject,
    D: SchemaExample + Serialize + ApiObject,
{
    fn example() -> Self {
        let link = D::get_count_link(&"http://127.0.0.1:20350/api".to_owned());
        Self {
            max_page_size: 100,
            total_item_count: 462,
            page_start: 0,
            page_size: 9,
            page_nr: 0,
            group_by: Some("type".to_owned()),
            etag: "b76e1b17f19bf1ab4901c4b21a747fc4898e656b3ac3080983498b07515fb655".to_owned(),
            links: ApiPageLinks {
                self_: format!("{}?group_by=type&per_page=100&page=1", link),
                first: Some(format!("{}?group_by=type&per_page=100&page=0", link)),
                prev: Some(format!("{}?group_by=type&per_page=100&page=0", link)),
                next: Some(format!("{}?group_by=type&per_page=100&page=2", link)),
                last: Some(format!("{}?group_by=type&per_page=100&page=5", link)),
            },
            data: vec![ApiMinimalItem::<C>::example()],

            given_etag: "".to_owned(),
            base_url: "".to_owned(),
            server_max_page_size: 0,
            parent_object: D::example(),
        }
    }
}

impl<C, D> ApiCountPage<C, D>
where
    C: ApiObject + Default + Serialize + SchemaExample,
    D: ApiObject + Default + Serialize + SchemaExample,
{
    pub fn new(pagination: &ApiMinimalPagination, server_info: &State<ServerInfo>) -> Self {
        let server_info = server_info.inner().clone();
        let mut new_object = Self::default();
        new_object.base_url = server_info.base_url.clone();
        new_object.server_max_page_size = server_info.page_max_limit;
        new_object.max_page_size = server_info.default_max_page_size;
        if let Some(per_page) = pagination.per_page {
            // Make sure to not go over `page_max_limit`
            new_object.max_page_size = cmp::min(per_page, server_info.page_max_limit);
        }
        // make sure it is at least 1 (>=1)
        new_object.max_page_size = cmp::max(new_object.max_page_size, 1);
        if let Some(page) = pagination.page {
            new_object.page_start = page * new_object.max_page_size;
        }
        if let Some(etag) = &pagination.etag {
            new_object.given_etag = etag.clone();
        }

        new_object
    }

    /// Store the data in the object and construct links and calculate ETag.
    /// Return if true etag match with request tag.
    pub fn wrap(&mut self, list: Vec<C>) -> bool {
        self.data = self.warp_data_list(list);
        self.page_nr = self.page_start / self.max_page_size;
        self.set_links();
        self.set_etag()
    }

    fn set_links(&mut self) {
        let mut query_parameters = Vec::new();
        let qp_page = if self.page_start != 0 {
            format!("page={}", self.page_nr)
        } else {
            "".to_owned()
        };

        if self.max_page_size != self.server_max_page_size {
            query_parameters.push(format!("per_page={}", self.max_page_size));
        }

        if let Some(group_by) = &self.group_by {
            query_parameters.push(format!("group_by={}", group_by));
        }

        // Self
        let mut links = ApiPageLinks::default();
        let base_api_path = D::get_count_link(&self.base_url);
        if qp_page.is_empty() {
            links.self_ = format!("{}?{}", base_api_path, query_parameters.join("&"));
        } else {
            let mut local_qp = query_parameters.clone();
            local_qp.push(qp_page);
            links.self_ = format!("{}?{}", base_api_path, local_qp.join("&"));
        }
        // First
        if self.page_start >= 1 {
            let mut local_qp = query_parameters.clone();
            local_qp.push("page=0".to_owned());
            links.first = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        // Prev
        if self.page_start >= 1 {
            let mut local_qp = query_parameters.clone();
            local_qp.push(format!("page={}", self.page_nr - 1));
            links.prev = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        // Next
        if self.page_start + self.max_page_size < self.total_item_count {
            let mut local_qp = query_parameters.clone();
            local_qp.push(format!("page={}", self.page_nr + 1));
            links.next = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        // Last
        if self.page_start + self.max_page_size < self.total_item_count {
            let mut local_qp = query_parameters;
            local_qp.push(format!(
                "page={}",
                (self.total_item_count - 1) / self.max_page_size
            ));
            links.last = Some(format!("{}?{}", base_api_path, local_qp.join("&")));
        }
        self.links = links;
    }

    /// Hash the data using Sha256 to create the ETag.
    /// After this function is called no extra data should be added.
    /// (or it should be rehashed).
    fn set_etag(&mut self) -> bool {
        // If Sha256 is no longer strong enough or is broken it should and can be easily
        // replaced in this function.
        use sha2::{Digest, Sha256};
        // Reset any already set ETag (so this does not effect the hash)
        self.etag = "".to_owned();
        // Hash the data to create the etag.
        let mut hasher = Sha256::new();
        // Convert data to json string.
        // Conversion is done to eliminate non-public values to effect the hash.
        let json_data = serde_json::to_string(self).unwrap();
        hasher.update(json_data);
        // Convert to `String` and store result in etag
        self.etag = format!("{:x}", hasher.finalize());
        // Check if ETags match
        self.etag == self.given_etag
    }

    fn warp_data_list(&mut self, list: Vec<C>) -> Vec<ApiMinimalItem<C>> {
        let mut data = Vec::new();
        self.page_size = list.len() as u32;

        for item in list {
            data.push(ApiMinimalItem::wrap_new(item, &self.base_url));
        }

        data
    }
}

/// A Wrapper for an `ApiObject` that includes additional metadata.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
#[schemars(example = "Self::example")]
pub struct ApiMinimalItem<D>
where
    D: ApiObject + Serialize + SchemaExample,
{
    /// A unique string identifier for this type.
    #[serde(rename = "_type")]
    pub type_: String,
    /// The included data item.
    #[serde(flatten)]
    pub data: D,
    /// Server base url.
    /// Not included in response.
    #[serde(skip)]
    pub base_url: String,
}

impl<D> SchemaExample for ApiMinimalItem<D>
where
    D: SchemaExample + Serialize + ApiObject,
{
    fn example() -> Self {
        Self {
            type_: D::get_type(),
            data: D::example(),
            base_url: "".to_owned(),
        }
    }
}

impl<D> ApiMinimalItem<D>
where
    D: ApiObject + Default + Serialize + SchemaExample,
{
    pub fn new(server_info: &State<ServerInfo>) -> Self {
        let server_info = server_info.inner().clone();
        let mut new_object = Self::default();
        new_object.base_url = server_info.base_url;
        new_object
    }

    /// Store the data in the object and construct links.
    pub fn wrap(&mut self, item: D) {
        self.data = item;
        self.type_ = D::get_type();
    }

    /// Create and wrap the item.
    /// This is the same as doing:
    /// ```ignore
    /// let api_item = ApiMinimalItem::wrap_new(result_item, &server_info.base_url);
    /// // same as:
    /// let api_item = ApiMinimalItem::new(server_info);
    /// api_item.wrap(result_item);
    /// ```
    pub fn wrap_new(item: D, base_url: &str) -> ApiMinimalItem<D> {
        let mut return_object = ApiMinimalItem::default();
        return_object.base_url = base_url.to_string();
        return_object.wrap(item);
        return_object
    }
}

/// A Query Guard for pagination of lists of items.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
pub struct ApiPagination {
    /// Number of the page you want to request. (starting from page 0)
    page: Option<u32>,
    /// Number of maximum items per page. (at least 1)
    per_page: Option<u32>,
    /// Tag to identify the version of the page requested.
    /// [More info here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag).
    etag: Option<String>,
    /// Force the page to be ordered. "asc" = A-Z, "desc" = Z-A.
    order: Option<OrderTypes>,
    /// What field should the result be ordered by. Example: "id" or "name".
    /// If the field does not exist it will order by the default field. (usually "id")
    order_by: Option<String>,
}

/// A Query Guard for pagination of lists of items.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
pub struct ApiMinimalPagination {
    /// Number of the page you want to request. (starting from page 0)
    page: Option<u32>,
    /// Number of maximum items per page. (at least 1)
    per_page: Option<u32>,
    /// Tag to identify the version of the page requested.
    /// [More info here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag).
    etag: Option<String>,
}

/// Possible ways of sorting data
#[derive(Serialize, Deserialize, Clone, Debug, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OrderTypes {
    Asc,
    Desc,
}

/// From DB order to Api order.
impl From<df_st_db::OrderTypes> for OrderTypes {
    fn from(order: df_st_db::OrderTypes) -> Self {
        match order {
            df_st_db::OrderTypes::Asc => OrderTypes::Asc,
            df_st_db::OrderTypes::Desc => OrderTypes::Desc,
        }
    }
}

/// From Api order to DB order.
impl From<OrderTypes> for df_st_db::OrderTypes {
    fn from(order: OrderTypes) -> Self {
        match order {
            OrderTypes::Asc => df_st_db::OrderTypes::Asc,
            OrderTypes::Desc => df_st_db::OrderTypes::Desc,
        }
    }
}

impl fmt::Display for OrderTypes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            OrderTypes::Asc => write!(f, "asc"),
            OrderTypes::Desc => write!(f, "desc"),
        }
    }
}

/// Parse incoming query data and store in `ApiPagination`
impl<'q> FromQuery<'q> for ApiPagination {
    type Error = Error; //TODO Custom error

    fn from_query(query: Query<'q>) -> Result<Self, Self::Error> {
        let mut api_page_request = ApiPagination::default();
        for key in query {
            match key.key.url_decode()?.as_ref() {
                "page" => api_page_request.page = Some(key.value.parse::<u32>()?),
                "per_page" => api_page_request.per_page = Some(key.value.parse::<u32>()?),
                "etag" => api_page_request.etag = Some(key.value.parse::<String>()?),
                "order" => {
                    api_page_request.order = Some(match key.value.url_decode()?.as_ref() {
                        "desc" => OrderTypes::Desc,
                        _ => OrderTypes::Asc,
                    })
                }
                "order_by" => api_page_request.order_by = Some(key.value.parse::<String>()?),
                _ => {}
            }
        }
        Ok(api_page_request)
    }
}

/// Add support for OpenApi generator
impl<'r> OpenApiFromQuery<'r> for ApiPagination {
    fn query_multi_parameter(
        gen: &mut OpenApiGenerator,
        name: String,
        required: bool,
    ) -> rocket_okapi::Result<Vec<okapi::openapi3::Parameter>> {
        Ok(get_nested_query_parameters::<ApiPagination>(
            gen, name, required,
        ))
    }
}

/// Parse incoming query data and store in `ApiMinimalPagination`
impl<'q> FromQuery<'q> for ApiMinimalPagination {
    type Error = Error; //TODO Custom error

    fn from_query(query: Query<'q>) -> Result<Self, Self::Error> {
        let mut api_page_request = ApiMinimalPagination::default();
        for key in query {
            match key.key.url_decode()?.as_ref() {
                "page" => api_page_request.page = Some(key.value.parse::<u32>()?),
                "per_page" => api_page_request.per_page = Some(key.value.parse::<u32>()?),
                "etag" => api_page_request.etag = Some(key.value.parse::<String>()?),
                _ => {}
            }
        }
        Ok(api_page_request)
    }
}

/// Add support for OpenApi generator
impl<'r> OpenApiFromQuery<'r> for ApiMinimalPagination {
    fn query_multi_parameter(
        gen: &mut OpenApiGenerator,
        name: String,
        required: bool,
    ) -> rocket_okapi::Result<Vec<okapi::openapi3::Parameter>> {
        Ok(get_nested_query_parameters::<ApiMinimalPagination>(
            gen, name, required,
        ))
    }
}