reliefweb 0.1.2

A Rust client for the ReliefWeb API
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
use std::fmt;

use reqwest::Url;

/// `QueryProfile` specifies which sets of fields to include in result.
#[derive(Default)]
pub enum QueryProfile {
    /// Just the `title` or `name` field
    #[default]
    Minimal,
    /// All fields
    Full,
    /// Results suited to lists and tables
    List,
}

impl fmt::Display for QueryProfile {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            QueryProfile::Minimal => write!(f, "minimal"),
            QueryProfile::Full => write!(f, "full"),
            QueryProfile::List => write!(f, "list"),
        }
    }
}

/// A shorthand specification of sets of fields, filters and sort order for common use-cases. Similar to `profile` but with more opinions
#[derive(Default)]
pub enum QueryPreset {
    ///The default setting applies sensible status filters for most requests
    #[default]
    Minimal,
    ///Sorts by date for appropriate content types. Countries and sources sorted by id. Use this for list requests.
    Latest,
    /// Include archived disasters and expired jobs and training which otherwise would be excluded from results. This is useful for visualizing trends and performing analysis of past content.
    Analysis,
}

impl fmt::Display for QueryPreset {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            QueryPreset::Minimal => write!(f, "minimal"),
            QueryPreset::Latest => write!(f, "latest"),
            QueryPreset::Analysis => write!(f, "analysis"),
        }
    }
}

#[derive(Default, Debug, PartialEq)]
/// Specifies how to interpret spaces in queries. Can be AND or OR. Default value is OR.
pub enum FilterOperator {
    #[default]
    OR,
    AND,
}

impl fmt::Display for FilterOperator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            FilterOperator::AND => write!(f, "AND"),
            FilterOperator::OR => write!(f, "OR"),
        }
    }
}

/// Specifies a full-text filter for the query
#[derive(Default, Debug, PartialEq)]
pub struct QueryQuery {
    /// What to search for. Required for all queries.
    pub value: String,
    /// Which fields to query on. See [field tables](https://apidoc.reliefweb.int/fields-tables) for options.
    pub fields: Vec<String>,
    /// How to interpret spaces in the query. Can be AND or OR. Default value is OR.
    pub operator: Option<FilterOperator>,
}

/// `Narrows down the content to be searched in. These correspond to the 'refine' section of the search bar.
pub struct QueryFilter {
    ///Which field to filter on. See [field tables](https://apidoc.reliefweb.int/fields-tables).
    pub field: String,
    /// The value to filter for. Most of the possible values are pre-defined. If this is for a `date`, or numeric value (e.g. `id`), it can be a range defined by `from` and `to` values. If only `from` or `to` is present, then value will match those greater than or equal to or less than or equal to the value respectively. If `value` is missing, the filter will act on whether the field exists or not.
    pub value: String,
    /// How to combine filter array values or conditions. Can be AND or OR.
    pub operator: Option<FilterOperator>,
    /// Set to `true` to select all items that do not match the filter.
    pub negate: bool,
}

/// Specifies the sorting direction of results for a given field.
#[derive(Default)]
pub enum SortDirection {
    #[default]
    Asc,
    Desc,
}

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

/// Specifies how results should be sorted for a given field.
pub struct SortDescriptor {
    pub field: String,
    pub direction: SortDirection,
}

// Query parameters for filtering, sorting, and field selection.
///
/// Provides a builder-style API to chain filters, queries, sorting, and inclusion/exclusion of fields.
///
/// # Example
///
/// ```no_run
/// use reliefweb::{QueryParams, QueryProfile};
///
/// let params = QueryParams::new()
///     .limit(10)
///     .profile(QueryProfile::Minimal)
///     .include(vec!["title".to_string(), "source".to_string()]);
/// ```
#[derive(Default)]
pub struct QueryParams {
    /// Free-text search in given fields.
    pub query: Option<QueryQuery>,
    /// Narrows down content to be searched in. Corresponds to the 'refine' section in the web UI.
    pub filter: Vec<QueryFilter>,
    ///A helper for creating correct API calls, setting verbose=1 adds a details section to the response to display the query parameters as a JSON object.
    ///
    /// This is for checking how the GET parameters are translated into JSON, or that the POST parameters sent are as intended.
    pub verbose: Option<bool>,
    ///How many results to return. Must be between 0 and 1000, defaults to 10.
    pub limit: Option<u32>,
    /// How many results to skip. Used for paging through results or for getting more than the limit. Must be greater than 0, defaults to 0.
    pub offset: Option<u32>,
    ///  Sortable field names and their direction `desc` or `asc` in the form `field:order`. The order of the field names in the array will determine the priority of the sorting.
    ///
    /// Note: requests with a query will be sorted by relevance. If there is no `sort` specified, results may not be consistent.
    ///
    /// For the most recent results, use the preset `latest`.
    pub sort: Vec<SortDescriptor>,
    /// A shorthand specification for which sets of fields to include in result.
    pub profile: Option<QueryProfile>,
    /// A shorthand specification of sets of fields, filters and sort order for common use-cases. Similar to profile but with more opinions.
    pub preset: Option<QueryPreset>,
    /// Arrays of fields to return in the result. To be used in conjunction with the profile parameter to personalize the fields returned and streamline requests.
    pub include: Vec<String>,
    /// Arrays of fields to exclude from the result. To be used in conjunction with the profile parameter to personalize the fields returned and streamline requests.
    pub exclude: Vec<String>,
}

impl QueryParams {
    /// Create a default set of query parameters.
    pub fn new() -> Self {
        Self::default()
    }

    pub fn query(mut self, query: QueryQuery) -> Self {
        self.query = Some(query);
        self
    }

    pub fn filter(mut self, filter: QueryFilter) -> Self {
        self.filter.push(filter);
        self
    }

    pub fn filters(mut self, filters: Vec<QueryFilter>) -> Self {
        self.filter.extend(filters);
        self
    }

    pub fn verbose(mut self, v: bool) -> Self {
        self.verbose = Some(v);
        self
    }

    pub fn limit(mut self, l: u32) -> Self {
        self.limit = Some(l);
        self
    }

    pub fn offset(mut self, o: u32) -> Self {
        self.offset = Some(o);
        self
    }

    pub fn sort(mut self, sort: Vec<SortDescriptor>) -> Self {
        self.sort.extend(sort);
        self
    }

    pub fn profile(mut self, profile: QueryProfile) -> Self {
        self.profile = Some(profile);
        self
    }

    pub fn preset(mut self, preset: QueryPreset) -> Self {
        self.preset = Some(preset);
        self
    }

    pub fn include(mut self, include: Vec<String>) -> Self {
        self.include.extend(include);
        self
    }

    pub fn exclude(mut self, exclude: Vec<String>) -> Self {
        self.exclude.extend(exclude);
        self
    }
}

impl QueryParams {
    /// Add URL-encoded params from a given existing Url
    pub(crate) fn apply_to_url(&self, url: &mut Url) {
        let mut qp = url.query_pairs_mut();

        if let Some(v) = self.verbose {
            qp.append_pair("verbose", if v { "1" } else { "0" });
        }
        if let Some(l) = self.limit {
            qp.append_pair("limit", &l.to_string());
        }
        if let Some(o) = self.offset {
            qp.append_pair("offset", &o.to_string());
        }
        if let Some(profile) = &self.profile {
            qp.append_pair("profile", &profile.to_string());
        }
        if let Some(preset) = &self.preset {
            qp.append_pair("preset", &preset.to_string());
        }

        for inc in &self.include {
            qp.append_pair("fields[include][]", inc);
        }
        for exc in &self.exclude {
            qp.append_pair("fields[exclude][]", exc);
        }

        if let Some(query) = &self.query {
            qp.append_pair(&format!("query[value]"), &query.value);
            for (j, field) in query.fields.iter().enumerate() {
                qp.append_pair(&format!("query[fields][{j}]"), field);
            }
            if let Some(op) = &query.operator {
                qp.append_pair(&format!("query[operator]"), &op.to_string());
            }
        }

        if !self.filter.is_empty() {
            if self.filter.iter().any(|f| f.operator.is_some()) {
                let top_op = self
                    .filter
                    .iter()
                    .filter_map(|f| f.operator.as_ref())
                    .next()
                    .unwrap()
                    .to_string();
                qp.append_pair("filter[operator]", &top_op);
            }
            for (i, f) in self.filter.iter().enumerate() {
                qp.append_pair(&format!("filter[conditions][{i}][field]"), &f.field);
                qp.append_pair(&format!("filter[conditions][{i}][value][]"), &f.value);
                if f.negate {
                    qp.append_pair(&format!("filter[conditions][{i}][negate]"), "1");
                }
                if let Some(op) = &f.operator {
                    qp.append_pair(
                        &format!("filter[conditions][{i}][operator]"),
                        &op.to_string(),
                    );
                }
            }
        }

        for s in &self.sort {
            qp.append_pair("sort[]", &format!("{}:{}", s.field, s.direction));
        }
    }
}

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

    #[test]
    fn test_query_params_builder() {
        let qp = QueryParams::new()
            .verbose(true)
            .limit(50)
            .offset(10)
            .profile(QueryProfile::Full)
            .preset(QueryPreset::Analysis)
            .include(vec!["field1".into(), "field2".into()])
            .exclude(vec!["field3".into()])
            .query(QueryQuery {
                value: "search".into(),
                fields: vec!["title".into()],
                operator: Some(FilterOperator::AND),
            })
            .filter(QueryFilter {
                field: "status".into(),
                value: "active".into(),
                operator: Some(FilterOperator::OR),
                negate: false,
            })
            .sort(vec![SortDescriptor {
                field: "date".into(),
                direction: SortDirection::Desc,
            }]);

        assert_eq!(qp.verbose, Some(true));
        assert_eq!(qp.limit, Some(50));
        assert_eq!(qp.offset, Some(10));
        assert_eq!(qp.profile.unwrap().to_string(), "full");
        assert_eq!(qp.preset.unwrap().to_string(), "analysis");
        assert_eq!(qp.include, vec!["field1", "field2"]);
        assert_eq!(qp.exclude, vec!["field3"]);
        assert_eq!(
            qp.query,
            Some(QueryQuery {
                value: "search".to_string(),
                fields: vec!["title".to_string()],
                operator: Some(FilterOperator::AND)
            })
        );
        assert_eq!(qp.filter.len(), 1);
        assert_eq!(qp.sort.len(), 1);
    }

    #[test]
    fn test_apply_to_url_basic() {
        let mut url = Url::parse("https://example.com/api").unwrap();

        let qp = QueryParams::new().verbose(true).limit(25).offset(5);

        qp.apply_to_url(&mut url);

        let query: Vec<(_, _)> = url.query_pairs().collect();
        assert!(query.contains(&("verbose".into(), "1".into())));
        assert!(query.contains(&("limit".into(), "25".into())));
        assert!(query.contains(&("offset".into(), "5".into())));
    }

    #[test]
    fn test_apply_to_url_include_exclude() {
        let mut url = Url::parse("https://example.com/api").unwrap();

        let qp = QueryParams::new()
            .include(vec!["title".into(), "summary".into()])
            .exclude(vec!["internal".into()]);

        qp.apply_to_url(&mut url);

        let query: Vec<(_, _)> = url.query_pairs().collect();
        assert!(query.contains(&("fields[include][]".into(), "title".into())));
        assert!(query.contains(&("fields[include][]".into(), "summary".into())));
        assert!(query.contains(&("fields[exclude][]".into(), "internal".into())));
    }

    #[test]
    fn test_apply_to_url_queries() {
        let mut url = Url::parse("https://example.com/api").unwrap();

        let qp = QueryParams::new().query(QueryQuery {
            value: "foo".into(),
            fields: vec!["title".into(), "content".into()],
            operator: Some(FilterOperator::AND),
        });

        qp.apply_to_url(&mut url);

        let query: Vec<(_, _)> = url.query_pairs().collect();
        assert!(query.contains(&("query[value]".into(), "foo".into())));
        assert!(query.contains(&("query[fields][0]".into(), "title".into())));
        assert!(query.contains(&("query[fields][1]".into(), "content".into())));
        assert!(query.contains(&("query[operator]".into(), "AND".into())));
    }

    #[test]
    fn test_apply_to_url_filters() {
        let mut url = Url::parse("https://example.com/api").unwrap();

        let qp = QueryParams::new().filter(QueryFilter {
            field: "status".into(),
            value: "active".into(),
            operator: Some(FilterOperator::OR),
            negate: true,
        });

        qp.apply_to_url(&mut url);

        let query: Vec<(_, _)> = url.query_pairs().collect();
        assert!(query.contains(&("filter[operator]".into(), "OR".into())));
        assert!(query.contains(&("filter[conditions][0][field]".into(), "status".into())));
        assert!(query.contains(&("filter[conditions][0][value][]".into(), "active".into())));
        assert!(query.contains(&("filter[conditions][0][negate]".into(), "1".into())));
    }

    #[test]
    fn test_apply_to_url_sort() {
        let mut url = Url::parse("https://example.com/api").unwrap();

        let qp = QueryParams::new().sort(vec![SortDescriptor {
            field: "date".into(),
            direction: SortDirection::Desc,
        }]);

        qp.apply_to_url(&mut url);

        let query: Vec<(_, _)> = url.query_pairs().collect();
        assert!(query.contains(&("sort[]".into(), "date:desc".into())));
    }
}