df_st_api 0.3.0-development-1

Starting an API server for the DF Storyteller project.
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
use crate::api_errors::APIErrorBadRequest;
use crate::api_objects::ApiObject;
use crate::pagination::{ApiItem, ApiPagination, OrderTypes};
use crate::ServerInfo;
use df_st_core::fillable::{Fillable, Filler};
use df_st_core::SchemaExample;
use df_st_db::{string_filter, DBObject, MatchBy};
use failure::Error;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use rocket::State;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::cmp;
use std::collections::HashMap;
use std::fmt::Debug;

/// 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>,
    /// Allows filtering over a property.
    /// The property has to be of type `String` or `i32`, so it will not work for all properties.
    /// Example: "type" or "year".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter_by: Option<String>,
    /// The values that is used as the filter. Example: "hf_died" or "1000".
    /// If value is wrong type a `400 Bad Request` will be returned.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter_value: Option<String>,
    /// Don't load nested items. This will speed up page loads but will not fill in all the data.
    /// Fields that can be used for ordering are usually the only field that are returned.
    /// - `Some(false)` If value is not set, or set to "false" or "0" (same result default)
    /// - `Some(true)` If value is set to ""(empty), "true" or "1"
    /// - `None` If any other value this will add all the data to the response (default)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimal_data: Option<bool>,
    /// 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()),
            filter_by: Some("type".to_owned()),
            filter_value: Some("library".to_owned()),
            minimal_data: Some(false),
            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.filter_by = pagination.filter_by.clone();
        new_object.filter_value = pagination.filter_value.clone();
        new_object.minimal_data = pagination.minimal_data;
        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));
        }

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

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

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

        // 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));
        }

        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,
        }
    }

    pub fn get_string_filter(&self) -> HashMap<String, String> {
        if self.filter_by.is_some() && self.filter_value.is_some() {
            let filter_by = self.filter_by.clone().unwrap_or_default();
            let filter_value = self.filter_value.clone().unwrap_or_default();
            string_filter![filter_by => filter_value]
        } else {
            string_filter![]
        }
    }

    pub fn add_int_filter(&self, mut int_filter: HashMap<String, i32>) -> HashMap<String, i32> {
        if self.filter_by.is_some() && self.filter_value.is_some() {
            let filter_by = self.filter_by.clone().unwrap_or_default();
            let filter_value = self.filter_value.clone().unwrap_or_default();
            if let Ok(value) = filter_value.parse::<i32>() {
                int_filter.insert(filter_by, value);
            }
            int_filter
        } else {
            int_filter
        }
    }

    pub fn match_fields<T, C, DB>(&mut self) -> Result<(), APIErrorBadRequest>
    where
        T: DBObject<C, DB>,
        // Traits needed for `DBObject`
        C: Fillable + Filler<C, DB> + Default + Debug + Clone,
        DB: PartialEq<C> + Debug + Clone,
    {
        if self.order_by.is_some() {
            self.order_by = match T::match_field_by_opt(self.order_by.clone(), MatchBy::OrderBy) {
                Some(order_by) => Some(order_by),
                None => {
                    let message = format!(
                        "Order by field `{}` does not exists. Allowed fields are: {}",
                        self.order_by.as_ref().unwrap(),
                        T::match_field_by(MatchBy::OrderBy).join(", "),
                    );
                    error!("{}", message);
                    return Err(APIErrorBadRequest::from(message));
                }
            }
        }
        // Check if both `filter_by` and `filter_value` is set
        if (self.filter_by.is_some() && self.filter_value.is_none())
            || (self.filter_by.is_none() && self.filter_value.is_some())
        {
            return Err(APIErrorBadRequest::from(
                "Both `filter_by` and `filter_value` \
                have to be provided for the filter to work.",
            ));
        }
        if self.filter_by.is_some() {
            // If the field is a integer field, check if value is integer
            if T::match_field_by_opt(self.filter_by.clone(), MatchBy::IntFilterBy).is_some() {
                let filter_value = self.filter_value.clone().unwrap_or_default();
                match filter_value.parse::<i32>() {
                    Ok(_) => {}
                    Err(err) => match err.to_string().as_ref() {
                        "invalid digit found in string" => {
                            let message = format!(
                                "Filter error value `{}` is not an integer, \
                                please insert a number.",
                                filter_value
                            );
                            error!("{}", message);
                            return Err(APIErrorBadRequest::from(message));
                        }
                        _ => {
                            error!("Filter error: {}", err.to_string());
                            return Err(APIErrorBadRequest::from(Error::from(err)));
                        }
                    },
                }
            }
            self.filter_by = match T::match_field_by_opt(self.filter_by.clone(), MatchBy::FilterBy)
            {
                Some(filter_by) => Some(filter_by),
                None => {
                    let message = format!(
                        "Filter by field `{}` does not exists. Allowed fields are: {}",
                        self.filter_by.as_ref().unwrap(),
                        T::match_field_by(MatchBy::FilterBy).join(", "),
                    );
                    error!("{}", message);
                    return Err(APIErrorBadRequest::from(message));
                }
            }
        }
        Ok(())
    }

    pub fn get_nested_items(&self) -> bool {
        match self.minimal_data {
            Some(true) => false,
            Some(false) => true,
            // default is to add data
            None => true,
        }
    }
}

/// 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(),
            ),
        }
    }
}