EasyAlgolia 1.0.4

EasyAlgolia is a Rust crate designed for utilizing the Algolia admin client. It simplifies the process of updating and inserting documents into Algolia's search index.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Easy Algolia is unofficial Rust client for algolia admin to update and insert data in Algolia
//! Search Engine

#[allow(non_snake_case)]
pub mod client_builder;
pub mod error;
use error::EasyAlgoliaError;
use secrecy::{
    ExposeSecret,
    Secret,
};
pub mod algoliaobject;
use crate::algoliaobject::AlgoliaObject;
use reqwest::Client as Rq;

/// index object to store the index of the Algoia
pub struct Index {
    index: String,
}
impl Index {
    fn index(&self) -> &str {
        &self.index
    }
}

impl From<String> for Index {
    fn from(s: String) -> Self {
        Self { index: s }
    }
}

impl From<&str> for Index {
    fn from(s: &str) -> Self {
        Self {
            index: String::from(s),
        }
    }
}

/// setting for Algolia Index
/// This seeting can be loaded and can bet set from backend using [client.update_index_setting](crate::Client::update_index_setting) method
/// ```ignore
///    let my_index:Index = "MyIndex".into() ;
///    let mut setting = client.get_index_setting(my_index).await;
///    // set default setting for index
///    let new_setting = AlgoliaIndexSetting::Default();
///    // update setting
///    client.update_index_setting(my_index,new_setting)
/// ```
///    
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct AlgoliaIndexSetting {
    pub min_word_size_for_1_typo: u32,
    pub min_word_size_for_2_typos: u32,
    pub hits_per_page: u32,
    pub max_values_per_facet: u32,
    pub version: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub searchable_attributes: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub numeric_attributes_to_index: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes_to_retrieve: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unretrievable_attributes: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub optional_words: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes_for_faceting: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes_to_snippet: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes_to_highlight: Option<Vec<String>>,
    pub pagination_limited_to: u32,
    pub attribute_for_distinct: Option<String>,
    pub exact_on_single_word_query: String,
    pub ranking: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_ranking: Option<Vec<String>>,
    pub separators_to_index: String,
    pub remove_words_if_no_results: String,
    pub query_type: String,
    pub highlight_pre_tag: String,
    pub highlight_post_tag: String,
    pub alternatives_as_exact: Vec<String>,
}

/// object Id struct for docs delete
/// This struct can be used to delete pre-existing docs in algoia
/// original self described document can be passed as well ( since it impls AlgoliaObj trait ) , but
/// since it consume the document its developers choice how to procced # Usage
/// ```ignore
///  // suppose you already have a document in Index named Games and with id 'god-of-war'
///  // to delete that document from that index you can use
///  let obj_id:ObjectId = "god-of-war".into();
///  let index:Index = "Games".into() ;
///  let client = Clientbuilder::build_from_env().unwarp();
///  client.delete_document_async(index,obj_id).await.unwarp();
///  ```

#[derive(serde::Serialize)]
pub struct ObjectId {
    obj_id: String,
}
impl From<String> for ObjectId {
    fn from(s: String) -> Self {
        Self { obj_id: s }
    }
}

impl From<&str> for ObjectId {
    fn from(s: &str) -> Self {
        Self {
            obj_id: String::from(s),
        }
    }
}

impl AlgoliaObject for ObjectId {
    fn get_object_id(&self) -> String {
        String::from(&self.obj_id)
    }
}

/// Client to interact with algolia
pub struct Client {
    api_key: Secret<String>,
    application_id: Secret<String>,
    client: Rq,
}

impl Client {
    pub(crate) fn new(api_key: &str, application_id: &str) -> Self {
        Self {
            api_key: Secret::new(String::from(api_key)),
            application_id: Secret::new(String::from(application_id)),
            client: Rq::new(),
        }
    }
    /// update or insert a data into given algolia index
    /// if the contained document objectId is present in algolia index, then this function will
    /// update document with new values if the document does default impls the implmentation
    /// AlgoliaObject , it will insert new doc of the given value in index # Arguments
    /// [EasyAlgoliaError](crate::Index)
    // # Examples
    /// ```ignore
    /// use EasyAlgolia::trait::AlgoliaObject;
    /// #[derive(serde::Serialize)]
    /// struct MyDoc{
    ///  pub obj_id:String,
    ///  pub name:String,
    ///  pub class:i32,
    ///  pub course:String
    ///  }
    ///
    /// impl AlgoliaObject for MyDoc{
    ///   fn get_object_id(&self) -> String {
    ///   &self.obj_id.into()
    /// }
    ///  let doc = MyDoc{
    ///   obj_id: String::from("some obj id") ,
    ///   ..Default::default()
    ///   } ;
    ///  client.put_document_async("someIndex".into(),doc)
    /// ```

    pub async fn put_document_async<T: AlgoliaObject>(
        &self,
        index: &Index,
        document: &T,
    ) -> Result<(), EasyAlgoliaError>
    where
        T: serde::Serialize + AlgoliaObject,
    {
        let mut is_object_is_present = false;
        let path = match document.get_object_id().as_str() {
            // if object id is not present in algolia doc then put random object id
            // random id is generted by algolia
            "" => {
                format!(
                    "https://{}.algolia.net/1/indexes/{}",
                    &self.application_id.expose_secret(),
                    index.index(),
                )
            }
            _ => {
                is_object_is_present = true;
                format!(
                    "https://{}.algolia.net/1/indexes/{}/{}",
                    &self.application_id.expose_secret(),
                    index.index(),
                    document.get_object_id()
                )
            }
        };
        let mut client = match is_object_is_present {
            true => self.client.put(path),
            false => self.client.post(path),
        };
        client = client.header("X-Algolia-API-Key", self.api_key.expose_secret());
        client = client.header(
            "X-Algolia-Application-Id",
            self.application_id.expose_secret(),
        );
        client = client.json(&document);

        match client.send().await {
            Ok(k) => {
                if k.status() > reqwest::StatusCode::from_u16(200).unwrap()
                    || k.status() < reqwest::StatusCode::from_u16(200).unwrap()
                {
                    return Err(EasyAlgoliaError::new(
                        error::ErrorKind::RequestError,
                        Some(k.text().await.unwrap()),
                    ));
                }

                Ok(())
            }
            Err(err) => Err(err.into()),
        }
    }

    /// same as [put_document_async](crate::Client::put_document_async) but blocking in nature
    /// /// under the hood it still uses asyn reqwest method only , but the runtime is block by
    /// `futures::executor::block_on`
    pub fn put_document<T: AlgoliaObject>(
        &self,
        index: &Index,
        document: &T,
    ) -> Result<(), EasyAlgoliaError>
    where
        T: serde::Serialize + AlgoliaObject,
    {
        let mut is_object_is_present = false;
        let path = match document.get_object_id().as_str() {
            // if object id is not present in algolia doc then put random object id
            // random id is generted by algolia
            "" => {
                format!(
                    "https://{}.algolia.net/1/indexes/{}",
                    &self.application_id.expose_secret(),
                    index.index(),
                )
            }
            _ => {
                is_object_is_present = true;
                format!(
                    "https://{}.algolia.net/1/indexes/{}/{}",
                    &self.application_id.expose_secret(),
                    index.index(),
                    document.get_object_id()
                )
            }
        };
        let mut client = match is_object_is_present {
            true => self.client.put(path),
            false => self.client.post(path),
        };
        client = client.header("X-Algolia-API-Key", self.api_key.expose_secret());
        client = client.header(
            "X-Algolia-Application-Id",
            self.application_id.expose_secret(),
        );
        client = client.json(&document);

        match futures::executor::block_on(client.send()) {
            Ok(k) => {
                if k.status() > reqwest::StatusCode::from_u16(200).unwrap()
                    || k.status() < reqwest::StatusCode::from_u16(200).unwrap()
                {
                    return Err(EasyAlgoliaError::new(
                        error::ErrorKind::RequestError,
                        Some(futures::executor::block_on(k.text()).unwrap()),
                    ));
                }

                Ok(())
            }
            Err(err) => Err(err.into()),
        }
    }

    /// update or insert a data into given algolia index
    /// if the contained document objectId is present in algolia index, then this function will
    /// update document with new values if the document does default impls the implmentation
    /// AlgoliaObject , it will insert new doc of the given value in index # Arguments
    /// [EasyAlgoliaError](crate::Index)
    // # Examples
    /// ```ignore
    /// use EasyAlgolia::trait::AlgoliaObject;
    /// #[derive(serde::Serialize)]
    /// struct MyDoc{
    ///  pub obj_id:String,
    ///  pub name:String,
    ///  pub class:i32,
    ///  pub course:String
    ///  }
    ///
    /// impl AlgoliaObject for MyDoc{
    ///   fn get_object_id(&self) -> String {
    ///   &self.obj_id.into()
    /// }
    ///  let doc = MyDoc{
    ///   obj_id: String::from("some obj id") ,
    ///   ..Default::default()
    ///   } ;
    ///  client.put_document_async("someIndex".into(),doc)
    /// ```
    pub async fn delete_document_async<T>(
        &self,
        index: &Index,
        document: T,
    ) -> Result<(), EasyAlgoliaError>
    where
        T: serde::Serialize + AlgoliaObject,
    {
        let path = match document.get_object_id().as_str() {
            "" => {
                return Err(EasyAlgoliaError::new(
                    error::ErrorKind::RequestError,
                    Some("object id must be present for document delete method".into()),
                ));
            }
            _ => {
                format!(
                    "https://{}.algolia.net/1/indexes/{}/{}",
                    &self.application_id.expose_secret(),
                    index.index(),
                    document.get_object_id()
                )
            }
        };

        let mut client = self.client.delete(path);
        client = client.header("X-Algolia-API-Key", self.api_key.expose_secret());
        client = client.header(
            "X-Algolia-Application-Id",
            self.application_id.expose_secret(),
        );
        match client.send().await {
            Ok(k) => {
                if k.status() > reqwest::StatusCode::from_u16(200).unwrap()
                    || k.status() < reqwest::StatusCode::from_u16(200).unwrap()
                {
                    return Err(EasyAlgoliaError::new(
                        error::ErrorKind::RequestError,
                        Some(k.text().await.unwrap()),
                    ));
                }

                Ok(())
            }
            Err(err) => Err(err.into()),
        }
    }

    /// same as [delete_document_async](crate::Client::delete_document_async) but its synchronous in
    /// nature under the hood it still uses asyn reqwest method only , but the runtime is block
    /// by `futures::executor::block_on`
    pub fn delete_document<T>(&self, index: &Index, document: T) -> Result<(), EasyAlgoliaError>
    where
        T: serde::Serialize + AlgoliaObject,
    {
        let path = match document.get_object_id().as_str() {
            "" => {
                return Err(EasyAlgoliaError::new(
                    error::ErrorKind::RequestError,
                    Some("object id must be present for document delete method".into()),
                ));
            }
            _ => {
                format!(
                    "https://{}.algolia.net/1/indexes/{}/{}",
                    &self.application_id.expose_secret(),
                    index.index(),
                    document.get_object_id()
                )
            }
        };

        let mut client = self.client.delete(path);
        client = client.header("X-Algolia-API-Key", self.api_key.expose_secret());
        client = client.header(
            "X-Algolia-Application-Id",
            self.application_id.expose_secret(),
        );
        match futures::executor::block_on(client.send()) {
            Ok(k) => {
                if k.status() > reqwest::StatusCode::from_u16(200).unwrap()
                    || k.status() < reqwest::StatusCode::from_u16(200).unwrap()
                {
                    return Err(EasyAlgoliaError::new(
                        error::ErrorKind::RequestError,
                        Some(futures::executor::block_on(k.text()).unwrap()),
                    ));
                }

                Ok(())
            }
            Err(err) => Err(err.into()),
        }
    }
    
    /// get settings for a given index
    /// return setting from this function can be modfied and set, key sets to None will be replaced to default
    /// ```ignore
    ///    let index:Index = "SomeIndex".into(); 
    ///    let setting = client.get_index_setting().await?;
    /// ```
    pub async fn get_index_setting<T: AlgoliaObject>(
        &self,
        index: &Index,
    ) -> Result<AlgoliaIndexSetting, EasyAlgoliaError>
    where
        T: serde::Serialize + AlgoliaObject,
    {
        let path = format!(
            "https://{}.algolia.net/1/indexes/{}/settings",
            &self.application_id.expose_secret(),
            index.index()
        );
        let mut client = self.client.get(path);
        client = client.header("X-Algolia-API-Key", self.api_key.expose_secret());
        client = client.header(
            "X-Algolia-Application-Id",
            self.application_id.expose_secret(),
        );
        match client.send().await {
            Ok(k) => {
                if k.status() > reqwest::StatusCode::from_u16(200).unwrap()
                    || k.status() < reqwest::StatusCode::from_u16(200).unwrap()
                {
                    return Err(EasyAlgoliaError::new(
                        error::ErrorKind::RequestError,
                        Some(k.text().await.unwrap()),
                    ));
                } else {
                    let setting: AlgoliaIndexSetting = k
                        .json::<AlgoliaIndexSetting>()
                        .await
                        .map_err(|_| EasyAlgoliaError::new(error::ErrorKind::RequestError, None))?;

                    Ok(setting)
                }
            }
            Err(err) => Err(err.into()),
        }
    }


    /// upload settings for a given index
    /// key sets to None will be replaced to default
    /// ```ignore
    ///    let index:Index = "SomeIndex".into(); 
    ///    let index_setting = AlgoliaIndexSetting::default();
    ///    let setting = client.update_index_setting().await?;
    /// ```
    pub async fn update_index_setting<T: AlgoliaObject>(
        &self,
        index: &Index,
        setting: AlgoliaIndexSetting
    ) -> Result<(), EasyAlgoliaError>
    where
        T: serde::Serialize + AlgoliaObject,
    {
        let path = format!(
            "https://{}.algolia.net/1/indexes/{}/settings",
            &self.application_id.expose_secret(),
            index.index()
        );
        let mut client = self.client.put(path);
        client = client.header("X-Algolia-API-Key", self.api_key.expose_secret());
        client = client.header(
            "X-Algolia-Application-Id",
            self.application_id.expose_secret(),
        );
        client = client.json(&setting) ;
        match client.send().await {
            Ok(k) => {
                if k.status() > reqwest::StatusCode::from_u16(200).unwrap()
                    || k.status() < reqwest::StatusCode::from_u16(200).unwrap()
                {
                    return Err(EasyAlgoliaError::new(
                        error::ErrorKind::RequestError,
                        Some(k.text().await.unwrap()),
                    ));
                } else {
                    Ok(())
                }
            }
            Err(err) => Err(err.into()),
        }
    }
}