1
use std::{error::Error as StdError, sync::Arc};
2

            
3
use async_trait::async_trait;
4
use futures::TryStreamExt;
5
use mongodb::{
6
    action::Find,
7
    bson::{doc, Bson, DateTime, Document, Regex},
8
    Cursor as MongoDbCursor, Database,
9
};
10
use serde::{Deserialize, Serialize};
11

            
12
use super::super::client::{
13
    Client, ClientModel, Cursor, ListOptions, ListQueryCond, QueryCond, SortKey, UpdateQueryCond,
14
    Updates,
15
};
16

            
17
/// Model instance.
18
pub struct Model {
19
    /// The associated database connection.
20
    conn: Arc<Database>,
21
}
22

            
23
/// Cursor instance.
24
struct DbCursor {
25
    /// The associated collection cursor.
26
    cursor: MongoDbCursor<Schema>,
27
    /// (Useless) only for Cursor trait implementation.
28
    offset: u64,
29
}
30

            
31
/// MongoDB schema.
32
19635
#[derive(Deserialize, Serialize)]
33
struct Schema {
34
    #[serde(rename = "clientId")]
35
    client_id: String,
36
    #[serde(rename = "createdAt")]
37
    created_at: DateTime,
38
    #[serde(rename = "modifiedAt")]
39
    modified_at: DateTime,
40
    #[serde(rename = "clientSecret")]
41
    client_secret: Option<String>,
42
    #[serde(rename = "redirectUris")]
43
    redirect_uris: Vec<String>,
44
    scopes: Vec<String>,
45
    #[serde(rename = "userId")]
46
    user_id: String,
47
    name: String,
48
    #[serde(rename = "imageUrl")]
49
    image_url: Option<String>,
50
}
51

            
52
const COL_NAME: &'static str = "client";
53

            
54
impl Model {
55
    /// To create the model instance with a database connection.
56
7
    pub async fn new(conn: Arc<Database>) -> Result<Self, Box<dyn StdError>> {
57
7
        let model = Model { conn };
58
14
        model.init().await?;
59
7
        Ok(model)
60
7
    }
61
}
62

            
63
#[async_trait]
64
impl ClientModel for Model {
65
12
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
66
12
        let indexes = vec![
67
12
            doc! {"name": "clientId_1", "key": {"clientId": 1}, "unique": true},
68
12
            doc! {"name": "createdAt_1", "key": {"createdAt": 1}},
69
12
            doc! {"name": "modifiedAt_1", "key": {"modifiedAt": 1}},
70
12
            doc! {"name": "userId_1", "key": {"userId": 1}},
71
12
            doc! {"name": "name_1", "key": {"name": 1}},
72
12
        ];
73
12
        let command = doc! {
74
12
            "createIndexes": COL_NAME,
75
12
            "indexes": indexes,
76
12
        };
77
24
        self.conn.run_command(command).await?;
78
12
        Ok(())
79
24
    }
80

            
81
10
    async fn count(&self, cond: &ListQueryCond) -> Result<u64, Box<dyn StdError>> {
82
10
        let filter = get_list_query_filter(cond);
83
10
        let count = self
84
10
            .conn
85
10
            .collection::<Schema>(COL_NAME)
86
10
            .count_documents(filter)
87
20
            .await?;
88
10
        Ok(count)
89
20
    }
90

            
91
    async fn list(
92
        &self,
93
        opts: &ListOptions,
94
        cursor: Option<Box<dyn Cursor>>,
95
57
    ) -> Result<(Vec<Client>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
96
57
        let mut cursor = match cursor {
97
            None => {
98
46
                let filter = get_list_query_filter(opts.cond);
99
46
                Box::new(DbCursor::new(
100
46
                    build_find_options(opts, self.conn.collection::<Schema>(COL_NAME).find(filter))
101
92
                        .await?,
102
                ))
103
            }
104
11
            Some(cursor) => cursor,
105
        };
106

            
107
57
        let mut count: u64 = 0;
108
57
        let mut list = Vec::new();
109
985
        while let Some(item) = cursor.try_next().await? {
110
939
            list.push(item);
111
939
            if let Some(cursor_max) = opts.cursor_max {
112
880
                count += 1;
113
880
                if count >= cursor_max {
114
11
                    return Ok((list, Some(cursor)));
115
869
                }
116
59
            }
117
        }
118
46
        Ok((list, None))
119
114
    }
120

            
121
863
    async fn get(&self, cond: &QueryCond) -> Result<Option<Client>, Box<dyn StdError>> {
122
863
        let filter = get_query_filter(cond);
123
863
        let mut cursor = self
124
863
            .conn
125
863
            .collection::<Schema>(COL_NAME)
126
863
            .find(filter)
127
1726
            .await?;
128
863
        if let Some(item) = cursor.try_next().await? {
129
846
            return Ok(Some(Client {
130
846
                client_id: item.client_id,
131
846
                created_at: item.created_at.into(),
132
846
                modified_at: item.modified_at.into(),
133
846
                client_secret: item.client_secret,
134
846
                redirect_uris: item.redirect_uris,
135
846
                scopes: item.scopes,
136
846
                user_id: item.user_id,
137
846
                name: item.name,
138
846
                image_url: item.image_url,
139
846
            }));
140
17
        }
141
17
        Ok(None)
142
1726
    }
143

            
144
534
    async fn add(&self, client: &Client) -> Result<(), Box<dyn StdError>> {
145
534
        let item = Schema {
146
534
            client_id: client.client_id.clone(),
147
534
            created_at: client.created_at.into(),
148
534
            modified_at: client.modified_at.into(),
149
534
            client_secret: client.client_secret.clone(),
150
534
            redirect_uris: client.redirect_uris.clone(),
151
534
            scopes: client.scopes.clone(),
152
534
            user_id: client.user_id.clone(),
153
534
            name: client.name.clone(),
154
534
            image_url: client.image_url.clone(),
155
534
        };
156
534
        self.conn
157
534
            .collection::<Schema>(COL_NAME)
158
534
            .insert_one(item)
159
1069
            .await?;
160
533
        Ok(())
161
1068
    }
162

            
163
10
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
164
10
        let filter = get_query_filter(cond);
165
10
        self.conn
166
10
            .collection::<Schema>(COL_NAME)
167
10
            .delete_many(filter)
168
20
            .await?;
169
10
        Ok(())
170
20
    }
171

            
172
    async fn update(
173
        &self,
174
        cond: &UpdateQueryCond,
175
        updates: &Updates,
176
14
    ) -> Result<(), Box<dyn StdError>> {
177
14
        let filter = get_update_query_filter(cond);
178
14
        if let Some(updates) = get_update_doc(updates) {
179
13
            self.conn
180
13
                .collection::<Schema>(COL_NAME)
181
13
                .update_one(filter, updates)
182
26
                .await?;
183
1
        }
184
14
        return Ok(());
185
28
    }
186
}
187

            
188
impl DbCursor {
189
    /// To create the cursor instance with a collection cursor.
190
46
    pub fn new(cursor: MongoDbCursor<Schema>) -> Self {
191
46
        DbCursor { cursor, offset: 0 }
192
46
    }
193
}
194

            
195
#[async_trait]
196
impl Cursor for DbCursor {
197
985
    async fn try_next(&mut self) -> Result<Option<Client>, Box<dyn StdError>> {
198
985
        if let Some(item) = self.cursor.try_next().await? {
199
939
            self.offset += 1;
200
939
            return Ok(Some(Client {
201
939
                client_id: item.client_id,
202
939
                created_at: item.created_at.into(),
203
939
                modified_at: item.modified_at.into(),
204
939
                client_secret: item.client_secret,
205
939
                redirect_uris: item.redirect_uris,
206
939
                scopes: item.scopes,
207
939
                user_id: item.user_id,
208
939
                name: item.name,
209
939
                image_url: item.image_url,
210
939
            }));
211
46
        }
212
46
        Ok(None)
213
1970
    }
214

            
215
4
    fn offset(&self) -> u64 {
216
4
        self.offset
217
4
    }
218
}
219

            
220
/// Transforms query conditions to the MongoDB document.
221
873
fn get_query_filter(cond: &QueryCond) -> Document {
222
873
    let mut filter = Document::new();
223
873
    if let Some(value) = cond.user_id {
224
12
        filter.insert("userId", value);
225
861
    }
226
873
    if let Some(value) = cond.client_id {
227
871
        filter.insert("clientId", value);
228
871
    }
229
873
    filter
230
873
}
231

            
232
/// Transforms query conditions to the MongoDB document.
233
56
fn get_list_query_filter(cond: &ListQueryCond) -> Document {
234
56
    let mut filter = Document::new();
235
56
    if let Some(value) = cond.user_id {
236
25
        filter.insert("userId", value);
237
31
    }
238
56
    if let Some(value) = cond.client_id {
239
4
        filter.insert("clientId", value);
240
52
    }
241
56
    if let Some(value) = cond.name_contains {
242
8
        filter.insert(
243
8
            "name",
244
8
            Regex {
245
8
                pattern: value.to_string(),
246
8
                options: "i".to_string(),
247
8
            },
248
8
        );
249
48
    }
250
56
    filter
251
56
}
252

            
253
/// Transforms model options to the options.
254
46
fn build_find_options<'a, T>(opts: &ListOptions, mut find: Find<'a, T>) -> Find<'a, T>
255
46
where
256
46
    T: Send + Sync,
257
46
{
258
46
    if let Some(offset) = opts.offset {
259
10
        find = find.skip(offset);
260
36
    }
261
46
    if let Some(limit) = opts.limit {
262
25
        if limit > 0 {
263
24
            find = find.limit(limit as i64);
264
24
        }
265
21
    }
266
46
    if let Some(sort_list) = opts.sort.as_ref() {
267
38
        if sort_list.len() > 0 {
268
37
            let mut sort_opts = Document::new();
269
44
            for cond in sort_list.iter() {
270
44
                let key = match cond.key {
271
11
                    SortKey::CreatedAt => "createdAt",
272
4
                    SortKey::ModifiedAt => "modifiedAt",
273
29
                    SortKey::Name => "name",
274
                };
275
44
                if cond.asc {
276
37
                    sort_opts.insert(key.to_string(), 1);
277
37
                } else {
278
7
                    sort_opts.insert(key.to_string(), -1);
279
7
                }
280
            }
281
37
            find = find.sort(sort_opts);
282
1
        }
283
8
    }
284
46
    find
285
46
}
286

            
287
/// Transforms query conditions to the MongoDB document.
288
14
fn get_update_query_filter(cond: &UpdateQueryCond) -> Document {
289
14
    doc! {
290
14
        "userId": cond.user_id,
291
14
        "clientId": cond.client_id,
292
14
    }
293
14
}
294

            
295
/// Transforms the model object to the MongoDB document.
296
14
fn get_update_doc(updates: &Updates) -> Option<Document> {
297
14
    let mut count = 0;
298
14
    let mut document = Document::new();
299
14
    if let Some(value) = updates.modified_at.as_ref() {
300
13
        document.insert(
301
13
            "modifiedAt",
302
13
            DateTime::from_millis(value.timestamp_millis()),
303
13
        );
304
13
        count += 1;
305
13
    }
306
14
    if let Some(value) = updates.client_secret.as_ref() {
307
3
        match value {
308
1
            None => {
309
1
                document.insert("clientSecret", Bson::Null);
310
1
            }
311
2
            Some(value) => {
312
2
                document.insert("clientSecret", value);
313
2
            }
314
        }
315
3
        count += 1;
316
11
    }
317
14
    if let Some(value) = updates.redirect_uris {
318
8
        document.insert("redirectUris", value);
319
8
        count += 1;
320
8
    }
321
14
    if let Some(value) = updates.scopes {
322
8
        document.insert("scopes", value);
323
8
        count += 1;
324
8
    }
325
14
    if let Some(value) = updates.name {
326
5
        document.insert("name", value);
327
5
        count += 1;
328
9
    }
329
14
    if let Some(value) = updates.image_url.as_ref() {
330
8
        match value {
331
4
            None => {
332
4
                document.insert("imageUrl", Bson::Null);
333
4
            }
334
4
            Some(value) => {
335
4
                document.insert("imageUrl", value);
336
4
            }
337
        }
338
8
        count += 1;
339
6
    }
340
14
    if count == 0 {
341
1
        return None;
342
13
    }
343
13
    Some(doc! {"$set": document})
344
14
}