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
use cipherstash_grpc::api::queries;

use crate::indexer::query::Query;

pub enum AggregateType {
    Count = 0,
}

impl From<AggregateType> for queries::Aggregate {
    fn from(aggregate_type: AggregateType) -> Self {
        let r#type = match aggregate_type {
            AggregateType::Count => queries::aggregate::AggregateType::Count,
        }
        .into();
        queries::Aggregate { r#type }
    }
}

pub enum Direction {
    Asc,
    Desc,
}

impl From<Direction> for i32 {
    fn from(direction: Direction) -> Self {
        match direction {
            Direction::Asc => queries::ordering::Direction::Asc,
            Direction::Desc => queries::ordering::Direction::Desc,
        }
        .into()
    }
}

pub struct Ordering {
    pub(crate) index_name: String,
    pub(crate) direction: Direction,
}

pub struct QueryInput {
    pub(crate) limit: u32,
    pub(crate) query: Query,
    pub(crate) aggregates: Vec<AggregateType>,
    pub(crate) ordering: Vec<Ordering>,
    pub(crate) skip_results: bool,
    pub(crate) offset: u32,
}

impl QueryInput {
    pub fn builder(query: Query) -> QueryInputBuilder {
        QueryInputBuilder::new(query)
    }
}

pub struct QueryInputBuilder {
    aggregates: Vec<AggregateType>,
    limit: Option<u32>,
    offset: Option<u32>,
    ordering: Vec<Ordering>,
    query: Query,
    skip_results: Option<bool>,
}

impl QueryInputBuilder {
    fn new(query: Query) -> Self {
        QueryInputBuilder {
            aggregates: Vec::new(),
            limit: None,
            offset: None,
            ordering: Vec::new(),
            query,
            skip_results: None,
        }
    }

    pub fn aggregate(mut self, value: AggregateType) -> Self {
        self.aggregates.push(value);
        self
    }

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

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

    pub fn order_by(mut self, index_name: &str, direction: Direction) -> Self {
        self.ordering.push(Ordering {
            index_name: index_name.into(),
            direction,
        });
        self
    }

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

    pub fn build(self) -> QueryInput {
        QueryInput {
            limit: self.limit.unwrap_or(100),
            query: self.query,
            aggregates: self.aggregates,
            ordering: self.ordering,
            skip_results: self.skip_results.unwrap_or(false),
            offset: self.offset.unwrap_or(0),
        }
    }
}