meilisearch_api_client/
lib.rs

1// Copyright 2019-2023 zTgx <beautifularea@gmail.com>.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! A well designed api client for MeiliSearch.
10//!
11//! CAVEAT: WIP
12//!
13//!
14//! # Quick Start
15//!
16//! To get you started quickly, the easiest and highest-level way to create
17//! index is to use [`create_index`]; 
18//!
19//! ```
20//! use meilisearch_api_client::{Config, client::Client, CreateIndexRequest};
21//!
22//! #[actix_rt::main]
23//! async fn main() -> std::io::Result<()> {
24//!    let uid  = "demo".to_string();
25//!    let name = "demoname".to_string();
26//!
27//!    // construct a request param
28//!    let req_data = CreateIndexRequest { uid, name, primary_key: None};
29//!
30//!    // config contains MeiliSearch server's host and port
31//!    let config = Config::new("http://127.0.0.1".to_string(), 7700);
32//!
33//!    // Client is api interface, using async/await.
34//!    let res = Client::new(config).create_index(req_data).await;
35//!    match res {
36//!        Ok(index) => {
37//!            println!("ceate index: {:?}", index);
38//!        },
39//!        Err(err) => {
40//!            println!("err: {:?}", err);
41//!        }
42//!     }
43//!     
44//!     Ok(())
45//! }
46//!
47//! ```
48//! Output:
49//! ```
50//! {"name":"demoname","uid":"demo","createdAt":"2020-05-14T08:56:24.483670375Z","updatedAt":"2020-05-14T08:56:24.484410846Z","primaryKey":null}
51//! ```
52//!
53//! # Installation
54//! 
55//! This crate requires a MeiliSearch server to run. See [here](https://docs.meilisearch.com/guides/advanced_guides/installation.html#download-and-launch) to install and run MeiliSearch.  
56//! For the user guide and further documentation, can be found
57//! [here](https://docs.meilisearch.com/)
58//! 
59
60mod indexes;
61mod documents;
62
63mod rest_helper;
64mod constants;
65
66/// Module containing all the api interfaces
67pub mod client;
68
69/// Module containing ServiceError
70pub mod error;
71
72use serde::{Deserialize, Serialize};
73use serde::ser::{Serializer, SerializeStruct};
74use serde::de::DeserializeOwned;
75use std::fmt::Debug;
76use std::fmt::Display;
77
78/// Including sever's host and port
79#[derive(Debug)]
80pub struct Config {
81    pub host: String,
82    pub port: usize,
83}
84
85impl Config {
86    pub fn new(host: String, port: usize) -> Self {
87        Config {
88            host,
89            port
90        }
91    }
92
93    pub fn get_url(&self) -> String {
94        self.host.as_str().to_owned() + ":" + self.port.to_string().as_str()
95    }
96}
97
98/// Index structure
99#[derive(Serialize, Deserialize, Debug)]
100pub struct Index {
101    pub uid : String,
102    pub name: String,
103
104    #[serde(rename="createdAt")]
105    pub created_at: String,
106
107    #[serde(rename="updatedAt")]
108    pub updated_at: String,
109
110    #[serde(rename="primaryKey")]
111    pub primary_key: String,
112}
113
114/// Collection of Indexes
115#[derive(Serialize, Deserialize, Debug)]
116pub struct Indexes {
117    pub indexes: Vec<Index>
118}
119impl Indexes {
120    pub fn new(indexes: Vec<Index>) -> Self {
121        Indexes {
122            indexes
123        }
124    }
125}
126
127/// Including create index's params
128#[derive(Deserialize, Debug)]
129pub struct CreateIndexRequest {
130    pub uid: String,
131    pub name: String,
132
133    #[serde(rename="primaryKey")]
134    pub primary_key: Option<String>
135}
136impl CreateIndexRequest {
137    pub fn new(uid: String, name: String, primary_key: Option<String>) -> Self {
138        CreateIndexRequest {
139            uid,
140            name,
141            primary_key
142        }
143    }
144}
145impl Serialize for CreateIndexRequest {
146    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
147    where
148        S: Serializer,
149    {
150        let mut state = serializer.serialize_struct("CreateIndexRequest", 3)?;
151
152        state.serialize_field("uid", &self.uid)?;
153        state.serialize_field("name", &self.name)?;
154
155        if self.primary_key.is_some () {
156            state.serialize_field("primaryKey", &self.primary_key)?;
157        } 
158
159        state.end()
160    }
161}
162
163/// Including update index's params
164#[derive(Serialize, Deserialize, Debug)]
165pub struct UpdateIndexRequest {
166    pub uid: String,
167    pub name: String,
168
169    #[serde(rename="primaryKey")]
170    pub primary_key: String,
171}
172
173impl UpdateIndexRequest {
174    pub fn new(uid: String, name: String, primary_key: String) -> Self {
175        UpdateIndexRequest {
176            uid,
177            name,
178            primary_key
179        }
180    }
181}
182
183/// Including delete index's params
184#[derive(Serialize, Deserialize, Debug)]
185pub struct DeleteIndexRequest {
186    pub uid: String,
187}
188
189impl DeleteIndexRequest {
190    pub fn new(uid: String) -> Self {
191        DeleteIndexRequest {
192            uid
193        }
194    }
195}
196
197/// Userdefined Document MUST impl
198pub trait Document: Serialize + DeserializeOwned + std::fmt::Debug {
199    type IDType: Display;
200
201    fn get_id(&self) -> &Self::IDType;
202}
203
204/// Including add documents request params
205#[derive(Serialize, Debug)]
206pub struct DocumentRequest <T: Document> {
207    pub uid: String,                // index id
208    pub documents: Option<Vec<T>>,  // user defined data
209}
210impl <T: Document> DocumentRequest <T> {
211    pub fn new(uid: String, documents: Option<Vec<T>>) -> Self {
212        DocumentRequest {
213            uid,
214            documents
215        }
216    }
217}
218
219/// Including documents related response
220#[derive(Serialize, Deserialize, Debug)]
221pub struct DocumentState {
222    #[serde(rename="updateId")]
223    pub update_id: usize,
224}
225