Skip to main content

flusso_query/handles/
sort.rs

1//! Sort keys: [`SortOrder`] and the scope-free [`Sort`] clause produced by
2//! `.asc()` / `.desc()` on a sortable handle (or `Geo::distance_sort`).
3
4use serde_json::{Map, Value};
5
6/// Sort direction.
7#[derive(Debug, Clone, Copy)]
8pub enum SortOrder {
9    /// Ascending.
10    Asc,
11    /// Descending.
12    Desc,
13}
14
15impl SortOrder {
16    pub(crate) fn as_str(self) -> &'static str {
17        match self {
18            SortOrder::Asc => "asc",
19            SortOrder::Desc => "desc",
20        }
21    }
22}
23
24/// A single sort key, produced by `.asc()` / `.desc()` on a sortable handle (or
25/// `Geo::distance_sort`). Scope-free.
26#[derive(Debug, Clone)]
27pub struct Sort {
28    value: Value,
29}
30
31impl Sort {
32    /// A field/order sort: `{ "<field>": { "order": "asc"|"desc" } }`.
33    pub(crate) fn new(field: &str, order: SortOrder) -> Self {
34        let mut order_body = Map::new();
35        order_body.insert(
36            "order".to_string(),
37            Value::String(order.as_str().to_string()),
38        );
39        let mut outer = Map::new();
40        outer.insert(field.to_string(), Value::Object(order_body));
41        Self {
42            value: Value::Object(outer),
43        }
44    }
45
46    /// A pre-built sort clause (e.g. `_geo_distance`).
47    pub(crate) fn raw(value: Value) -> Self {
48        Self { value }
49    }
50
51    pub(crate) fn to_value(&self) -> Value {
52        self.value.clone()
53    }
54}