diff --git a/Cargo.toml b/Cargo.toml index fd9db04b..efbcb219 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,28 +18,28 @@ log = "0.4" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" time = { version = "0.3.7", features = ["serde-well-known", "formatting", "parsing"] } -jsonwebtoken = { version = "9", default-features = false } yaup = "0.2.0" either = { version = "1.8.0", features = ["serde"] } thiserror = "1.0.37" meilisearch-index-setting-macro = { path = "meilisearch-index-setting-macro", version = "0.25.0" } +pin-project-lite = { version = "0.2.13", optional = true } +reqwest = { version = "0.12.3", optional = true, default-features = false, features = ["rustls-tls", "http2", "stream"] } +bytes = { version = "1.6", optional = true } +uuid = { version = "1.1.2", features = ["v4"] } +futures-io = "0.3.30" +futures = "0.3" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -futures = "0.3" -futures-io = "0.3.26" -isahc = { version = "1.0", features = ["http2", "text-decoding"], optional = true, default_features = false } -uuid = { version = "1.1.2", features = ["v4"] } +jsonwebtoken = { version = "9", default-features = false } [target.'cfg(target_arch = "wasm32")'.dependencies] -js-sys = "0.3.47" -web-sys = { version = "0.3", features = ["RequestInit", "Headers", "Window", "Response", "console"] } -wasm-bindgen = "0.2" +uuid = { version = "1.8.0", default-features = false, features = ["v4", "js"] } +web-sys = "0.3" wasm-bindgen-futures = "0.4" [features] -default = ["isahc", "isahc", "isahc-static-curl"] -isahc-static-curl = ["isahc", "isahc", "isahc/static-curl"] -isahc-static-ssl = ["isahc/static-ssl"] +default = ["reqwest"] +reqwest = ["dep:reqwest", "pin-project-lite", "bytes"] [dev-dependencies] futures-await-test = "0.3" @@ -56,3 +56,4 @@ lazy_static = "1.4" web-sys = "0.3" console_error_panic_hook = "0.1" big_s = "1.0.2" +insta = "1.38.0" diff --git a/README.md b/README.md index b0be50f9..5ed2b31a 100644 --- a/README.md +++ b/README.md @@ -108,9 +108,10 @@ struct Movie { } -fn main() { block_on(async move { +#[tokio::main(flavor = "current_thread")] +async fn main() { // Create a client (without sending any request so that can't fail) - let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); // An index is where the documents are stored. let movies = client.index("movies"); @@ -124,7 +125,7 @@ fn main() { block_on(async move { Movie { id: 5, title: String::from("Moana"), genres: vec!["Fantasy".to_string(), "Action".to_string()] }, Movie { id: 6, title: String::from("Philadelphia"), genres: vec!["Drama".to_string()] }, ], Some("id")).await.unwrap(); -})} +} ``` With the `uid`, you can check the status (`enqueued`, `canceled`, `processing`, `succeeded` or `failed`) of your documents addition using the [task](https://www.meilisearch.com/docs/reference/api/tasks#get-task). @@ -238,11 +239,11 @@ Json output: } ``` -#### Using users customized HttpClient +#### Customize the `HttpClient` -If you want to change the `HttpClient` you can incorporate using the `Client::new_with_client` method. -To use it, you need to implement the `HttpClient Trait`(`isahc` is used by default). -There are [using-reqwest-example](./examples/cli-app-with-reqwest) of using `reqwest`. +By default, the SDK uses [`reqwest`](https://docs.rs/reqwest/latest/reqwest/) to make http calls. +The SDK lets you customize the http client by implementing the `HttpClient` trait yourself and +initializing the `Client` with the `new_with_client` method. ## 🌐 Running in the Browser with WASM diff --git a/examples/cli-app-with-reqwest/Cargo.toml b/examples/cli-app-with-awc/Cargo.toml similarity index 67% rename from examples/cli-app-with-reqwest/Cargo.toml rename to examples/cli-app-with-awc/Cargo.toml index 54494538..bfdb09c2 100644 --- a/examples/cli-app-with-reqwest/Cargo.toml +++ b/examples/cli-app-with-awc/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "cli-app-with-reqwest" +name = "cli-app-with-awc" version = "0.0.0" edition = "2021" publish = false @@ -12,6 +12,9 @@ futures = "0.3" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" lazy_static = "1.4.0" -reqwest = "0.11.16" +awc = "3.4" async-trait = "0.1.51" -tokio = { version = "1.27.0", features = ["full"] } \ No newline at end of file +tokio = { version = "1.27.0", features = ["full"] } +yaup = "0.2.0" +tokio-util = { version = "0.7.10", features = ["full"] } +actix-rt = "2.9.0" diff --git a/examples/cli-app-with-reqwest/assets/clothes.json b/examples/cli-app-with-awc/assets/clothes.json similarity index 100% rename from examples/cli-app-with-reqwest/assets/clothes.json rename to examples/cli-app-with-awc/assets/clothes.json diff --git a/examples/cli-app-with-awc/src/main.rs b/examples/cli-app-with-awc/src/main.rs new file mode 100644 index 00000000..6c085dc5 --- /dev/null +++ b/examples/cli-app-with-awc/src/main.rs @@ -0,0 +1,257 @@ +use async_trait::async_trait; +use meilisearch_sdk::errors::Error; +use meilisearch_sdk::request::{parse_response, HttpClient, Method}; +use meilisearch_sdk::{client::*, settings::Settings}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::io::stdin; + +#[derive(Debug, Clone)] +pub struct AwcClient { + api_key: Option, +} + +impl AwcClient { + pub fn new(api_key: Option<&str>) -> Result { + Ok(AwcClient { + api_key: api_key.map(|key| key.to_string()), + }) + } +} + +#[async_trait(?Send)] +impl HttpClient for AwcClient { + async fn stream_request< + Query: Serialize + Send + Sync, + Body: futures::AsyncRead + Send + Sync + 'static, + Output: DeserializeOwned + 'static, + >( + &self, + url: &str, + method: Method, + content_type: &str, + expected_status_code: u16, + ) -> Result { + let mut builder = awc::ClientBuilder::new(); + if let Some(ref api_key) = self.api_key { + builder = builder.bearer_auth(api_key); + } + builder = builder.add_default_header(("User-Agent", "Rust client with Awc")); + let client = builder.finish(); + + let query = method.query(); + let query = yaup::to_string(query)?; + + let url = if query.is_empty() { + url.to_string() + } else { + format!("{url}?{query}") + }; + + let url = add_query_parameters(&url, method.query())?; + let request = client.request(verb(&method), &url); + + let mut response = if let Some(body) = method.into_body() { + let reader = tokio_util::compat::FuturesAsyncReadCompatExt::compat(body); + let stream = tokio_util::io::ReaderStream::new(reader); + request + .content_type(content_type) + .send_stream(stream) + .await + .map_err(|err| Error::Other(Box::new(err)))? + } else { + request + .send() + .await + .map_err(|err| Error::Other(Box::new(err)))? + }; + + let status = response.status().as_u16(); + let mut body = String::from_utf8( + response + .body() + .await + .map_err(|err| Error::Other(Box::new(err)))? + .to_vec(), + ) + .map_err(|err| Error::Other(Box::new(err)))?; + + if body.is_empty() { + body = "null".to_string(); + } + + parse_response(status, expected_status_code, &body, url.to_string()) + } +} + +#[actix_rt::main] +async fn main() { + let http_client = AwcClient::new(Some("masterKey")).unwrap(); + let client = Client::new_with_client("http://localhost:7700", Some("masterKey"), http_client); + + // build the index + build_index(&client).await; + + // enter in search queries or quit + loop { + println!("Enter a search query or type \"q\" or \"quit\" to quit:"); + let mut input_string = String::new(); + stdin() + .read_line(&mut input_string) + .expect("Failed to read line"); + match input_string.trim() { + "quit" | "q" | "" => { + println!("exiting..."); + break; + } + _ => { + search(&client, input_string.trim()).await; + } + } + } + // get rid of the index at the end, doing this only so users don't have the index without knowing + let _ = client.delete_index("clothes").await.unwrap(); +} + +async fn search(client: &Client, query: &str) { + // make the search query, which excutes and serializes hits into the + // ClothesDisplay struct + let query_results = client + .index("clothes") + .search() + .with_query(query) + .execute::() + .await + .unwrap() + .hits; + + // display the query results + if query_results.is_empty() { + println!("no results..."); + } else { + for clothes in query_results { + let display = clothes.result; + println!("{}", format_args!("{}", display)); + } + } +} + +async fn build_index(client: &Client) { + // reading and parsing the file + let content = include_str!("../assets/clothes.json"); + + // serialize the string to clothes objects + let clothes: Vec = serde_json::from_str(content).unwrap(); + + //create displayed attributes + let displayed_attributes = ["article", "cost", "size", "pattern"]; + + // Create ranking rules + let ranking_rules = ["words", "typo", "attribute", "exactness", "cost:asc"]; + + //create searchable attributes + let searchable_attributes = ["seaon", "article", "size", "pattern"]; + + // create the synonyms hashmap + let mut synonyms = std::collections::HashMap::new(); + synonyms.insert("sweater", vec!["cardigan", "long-sleeve"]); + synonyms.insert("sweat pants", vec!["joggers", "gym pants"]); + synonyms.insert("t-shirt", vec!["tees", "tshirt"]); + + //create the settings struct + let settings = Settings::new() + .with_ranking_rules(ranking_rules) + .with_searchable_attributes(searchable_attributes) + .with_displayed_attributes(displayed_attributes) + .with_synonyms(synonyms); + + //add the settings to the index + let result = client + .index("clothes") + .set_settings(&settings) + .await + .unwrap() + .wait_for_completion(client, None, None) + .await + .unwrap(); + + if result.is_failure() { + panic!( + "Encountered an error while setting settings for index: {:?}", + result.unwrap_failure() + ); + } + + // add the documents + let result = client + .index("clothes") + .add_or_update(&clothes, Some("id")) + .await + .unwrap() + .wait_for_completion(client, None, None) + .await + .unwrap(); + + if result.is_failure() { + panic!( + "Encountered an error while sending the documents: {:?}", + result.unwrap_failure() + ); + } +} + +/// Base search object. +#[derive(Serialize, Deserialize, Debug)] +pub struct Clothes { + id: usize, + seaon: String, + article: String, + cost: f32, + size: String, + pattern: String, +} + +/// Search results get serialized to this struct +#[derive(Serialize, Deserialize, Debug)] +pub struct ClothesDisplay { + article: String, + cost: f32, + size: String, + pattern: String, +} + +impl fmt::Display for ClothesDisplay { + // This trait requires `fmt` with this exact signature. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Write strictly the first element into the supplied output + // stream: `f`. Returns `fmt::Result` which indicates whether the + // operation succeeded or failed. Note that `write!` uses syntax which + // is very similar to `println!`. + write!( + f, + "result\n article: {},\n price: {},\n size: {},\n pattern: {}\n", + self.article, self.cost, self.size, self.pattern + ) + } +} + +fn add_query_parameters(url: &str, query: &Query) -> Result { + let query = yaup::to_string(query)?; + + if query.is_empty() { + Ok(url.to_string()) + } else { + Ok(format!("{url}?{query}")) + } +} + +fn verb(method: &Method) -> awc::http::Method { + match method { + Method::Get { .. } => awc::http::Method::GET, + Method::Delete { .. } => awc::http::Method::DELETE, + Method::Post { .. } => awc::http::Method::POST, + Method::Put { .. } => awc::http::Method::PUT, + Method::Patch { .. } => awc::http::Method::PATCH, + } +} diff --git a/examples/cli-app-with-reqwest/src/main.rs b/examples/cli-app-with-reqwest/src/main.rs deleted file mode 100644 index e5a53cde..00000000 --- a/examples/cli-app-with-reqwest/src/main.rs +++ /dev/null @@ -1,273 +0,0 @@ -use async_trait::async_trait; -use lazy_static::lazy_static; -use meilisearch_sdk::errors::Error; -use meilisearch_sdk::request::{ - add_query_parameters, parse_response, qualified_version, HttpClient, Method, -}; -use meilisearch_sdk::{client::*, settings::Settings}; -use serde::de::DeserializeOwned; -use serde::{Deserialize, Serialize}; -use serde_json::to_string; -use std::fmt; -use std::io::stdin; - -lazy_static! { - static ref CLIENT: Client = - Client::new_with_client("http://localhost:7700", Some("masterKey"), ReqwestClient); -} - -#[derive(Debug, Clone, Serialize)] -pub struct ReqwestClient; - -#[async_trait(?Send)] -impl HttpClient for ReqwestClient { - async fn request( - self, - url: &str, - apikey: Option<&str>, - method: Method, - expected_status_code: u16, - ) -> Result - where - Query: Serialize + Send + Sync, - Body: Serialize + Send + Sync, - Output: DeserializeOwned + 'static + Send, - { - let response = match &method { - Method::Get { query } => { - let url = add_query_parameters(url, query)?; - let client = reqwest::Client::new(); - let mut builder = client.request(reqwest::Method::GET, url.as_str()); - builder = builder.header(reqwest::header::USER_AGENT, qualified_version()); - if let Some(apikey) = apikey { - builder = - builder.header(reqwest::header::AUTHORIZATION, format!("Bearer {apikey}")); - } - let req = builder.build().unwrap(); - client.execute(req).await.unwrap() - } - Method::Post { query, body } => { - let url = add_query_parameters(url, query)?; - let client = reqwest::Client::new(); - let mut builder = client.request(reqwest::Method::POST, url.as_str()); - if let Some(apikey) = apikey { - builder = - builder.header(reqwest::header::AUTHORIZATION, format!("Bearer {apikey}")); - } - builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json"); - let req = builder.body(to_string(body).unwrap()).build().unwrap(); - client.execute(req).await.unwrap() - } - Method::Patch { query, body } => { - let url = add_query_parameters(url, query)?; - let client = reqwest::Client::new(); - let mut builder = client.request(reqwest::Method::PATCH, url.as_str()); - if let Some(apikey) = apikey { - builder = - builder.header(reqwest::header::AUTHORIZATION, format!("Bearer {apikey}")); - } - builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json"); - let req = builder.body(to_string(body).unwrap()).build().unwrap(); - client.execute(req).await.unwrap() - } - Method::Put { query, body } => { - let url = add_query_parameters(url, query)?; - let client = reqwest::Client::new(); - let mut builder = client.request(reqwest::Method::PUT, url.as_str()); - if let Some(apikey) = apikey { - builder = - builder.header(reqwest::header::AUTHORIZATION, format!("Bearer {apikey}")); - } - builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json"); - let req = builder.body(to_string(body).unwrap()).build().unwrap(); - client.execute(req).await.unwrap() - } - Method::Delete { query } => { - let url = add_query_parameters(url, query)?; - let client = reqwest::Client::new(); - let mut builder = client.request(reqwest::Method::DELETE, url.as_str()); - if let Some(apikey) = apikey { - builder = - builder.header(reqwest::header::AUTHORIZATION, format!("Bearer {apikey}")); - } - builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json"); - let req = builder.build().unwrap(); - client.execute(req).await.unwrap() - } - }; - - let status = response.status().as_u16(); - - let mut body = response.text().await.unwrap(); - - if body.is_empty() { - body = "null".to_string(); - } - - parse_response(status, expected_status_code, &body, url.to_string()) - } - - async fn stream_request< - 'a, - Query: Serialize + Send + Sync, - Body: futures::AsyncRead + Send + Sync + 'static, - Output: DeserializeOwned + 'static, - >( - self, - _url: &str, - _apikey: Option<&str>, - _method: Method, - _content_type: &str, - _expected_status_code: u16, - ) -> Result { - unimplemented!("stream_request is not implemented for ReqwestClient") - } -} - -#[tokio::main] -async fn main() { - // build the index - build_index().await; - - // enter in search queries or quit - loop { - println!("Enter a search query or type \"q\" or \"quit\" to quit:"); - let mut input_string = String::new(); - stdin() - .read_line(&mut input_string) - .expect("Failed to read line"); - match input_string.trim() { - "quit" | "q" | "" => { - println!("exiting..."); - break; - } - _ => { - search(input_string.trim()).await; - } - } - } - // get rid of the index at the end, doing this only so users don't have the index without knowing - let _ = CLIENT.delete_index("clothes").await.unwrap(); -} - -async fn search(query: &str) { - // make the search query, which excutes and serializes hits into the - // ClothesDisplay struct - let query_results = CLIENT - .index("clothes") - .search() - .with_query(query) - .execute::() - .await - .unwrap() - .hits; - - // display the query results - if query_results.is_empty() { - println!("no results..."); - } else { - for clothes in query_results { - let display = clothes.result; - println!("{}", format_args!("{}", display)); - } - } -} - -async fn build_index() { - // reading and parsing the file - let content = include_str!("../assets/clothes.json"); - - // serialize the string to clothes objects - let clothes: Vec = serde_json::from_str(content).unwrap(); - - //create displayed attributes - let displayed_attributes = ["article", "cost", "size", "pattern"]; - - // Create ranking rules - let ranking_rules = ["words", "typo", "attribute", "exactness", "cost:asc"]; - - //create searchable attributes - let searchable_attributes = ["seaon", "article", "size", "pattern"]; - - // create the synonyms hashmap - let mut synonyms = std::collections::HashMap::new(); - synonyms.insert("sweater", vec!["cardigan", "long-sleeve"]); - synonyms.insert("sweat pants", vec!["joggers", "gym pants"]); - synonyms.insert("t-shirt", vec!["tees", "tshirt"]); - - //create the settings struct - let settings = Settings::new() - .with_ranking_rules(ranking_rules) - .with_searchable_attributes(searchable_attributes) - .with_displayed_attributes(displayed_attributes) - .with_synonyms(synonyms); - - //add the settings to the index - let result = CLIENT - .index("clothes") - .set_settings(&settings) - .await - .unwrap() - .wait_for_completion(&CLIENT, None, None) - .await - .unwrap(); - - if result.is_failure() { - panic!( - "Encountered an error while setting settings for index: {:?}", - result.unwrap_failure() - ); - } - - // add the documents - let result = CLIENT - .index("clothes") - .add_or_update(&clothes, Some("id")) - .await - .unwrap() - .wait_for_completion(&CLIENT, None, None) - .await - .unwrap(); - - if result.is_failure() { - panic!( - "Encountered an error while sending the documents: {:?}", - result.unwrap_failure() - ); - } -} - -/// Base search object. -#[derive(Serialize, Deserialize, Debug)] -pub struct Clothes { - id: usize, - seaon: String, - article: String, - cost: f32, - size: String, - pattern: String, -} - -/// Search results get serialized to this struct -#[derive(Serialize, Deserialize, Debug)] -pub struct ClothesDisplay { - article: String, - cost: f32, - size: String, - pattern: String, -} - -impl fmt::Display for ClothesDisplay { - // This trait requires `fmt` with this exact signature. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Write strictly the first element into the supplied output - // stream: `f`. Returns `fmt::Result` which indicates whether the - // operation succeeded or failed. Note that `write!` uses syntax which - // is very similar to `println!`. - write!( - f, - "result\n article: {},\n price: {},\n size: {},\n pattern: {}\n", - self.article, self.cost, self.size, self.pattern - ) - } -} diff --git a/examples/cli-app/Cargo.toml b/examples/cli-app/Cargo.toml index b3e96b2a..d0230c7e 100644 --- a/examples/cli-app/Cargo.toml +++ b/examples/cli-app/Cargo.toml @@ -12,3 +12,4 @@ futures = "0.3" serde = { version="1.0", features = ["derive"] } serde_json = "1.0" lazy_static = "1.4.0" +yaup = "0.2.0" diff --git a/examples/cli-app/src/main.rs b/examples/cli-app/src/main.rs index 64b5cd17..43c61ffd 100644 --- a/examples/cli-app/src/main.rs +++ b/examples/cli-app/src/main.rs @@ -8,7 +8,7 @@ use std::io::stdin; // instantiate the client. load it once lazy_static! { - static ref CLIENT: Client = Client::new("http://localhost:7700", Some("masterKey")); + static ref CLIENT: Client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); } fn main() { diff --git a/examples/settings.rs b/examples/settings.rs index 7397a946..fa2b46ad 100644 --- a/examples/settings.rs +++ b/examples/settings.rs @@ -3,7 +3,7 @@ use meilisearch_sdk::{client::Client, indexes::Index, settings::Settings}; // we need an async runtime #[tokio::main(flavor = "current_thread")] async fn main() { - let client: Client = Client::new("http://localhost:7700", Some("masterKey")); + let client: Client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); // We try to create an index called `movies` with a primary_key of `movie_id`. let my_index: Index = client diff --git a/examples/web_app/src/lib.rs b/examples/web_app/src/lib.rs index 004914f7..f9e35d0d 100644 --- a/examples/web_app/src/lib.rs +++ b/examples/web_app/src/lib.rs @@ -14,7 +14,7 @@ mod document; use crate::document::{display, Crate}; lazy_static! { - static ref CLIENT: Client = Client::new("http://localhost:7700", Some("masterKey")); + static ref CLIENT: Client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); } struct Model { diff --git a/meilisearch-index-setting-macro/src/lib.rs b/meilisearch-index-setting-macro/src/lib.rs index d1b32379..06d3d811 100644 --- a/meilisearch-index-setting-macro/src/lib.rs +++ b/meilisearch-index-setting-macro/src/lib.rs @@ -128,7 +128,7 @@ fn get_index_config_implementation( quote! { #[::meilisearch_sdk::macro_helper::async_trait(?Send)] - impl ::meilisearch_sdk::documents::IndexConfig<::meilisearch_sdk::request::IsahcClient> for #struct_ident { + impl ::meilisearch_sdk::documents::IndexConfig for #struct_ident { const INDEX_STR: &'static str = #index_name; fn generate_settings() -> ::meilisearch_sdk::settings::Settings { @@ -140,7 +140,7 @@ fn get_index_config_implementation( #distinct_attr_token } - async fn generate_index(client: &::meilisearch_sdk::client::Client<::meilisearch_sdk::request::IsahcClient>) -> std::result::Result<::meilisearch_sdk::indexes::Index<::meilisearch_sdk::request::IsahcClient>, ::meilisearch_sdk::tasks::Task> { + async fn generate_index(client: &::meilisearch_sdk::client::Client) -> std::result::Result<::meilisearch_sdk::indexes::Index, ::meilisearch_sdk::tasks::Task> { return client.create_index(#index_name, #primary_key_token) .await.unwrap() .wait_for_completion(&client, ::std::option::Option::None, ::std::option::Option::None) diff --git a/meilisearch-test-macro/src/lib.rs b/meilisearch-test-macro/src/lib.rs index d20afbbf..28d4a440 100644 --- a/meilisearch-test-macro/src/lib.rs +++ b/meilisearch-test-macro/src/lib.rs @@ -91,7 +91,7 @@ pub fn meilisearch_test(params: TokenStream, input: TokenStream) -> TokenStream let meilisearch_api_key = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); )); outer_block.push(parse_quote!( - let client = Client::new(meilisearch_url, Some(meilisearch_api_key)); + let client = Client::new(meilisearch_url, Some(meilisearch_api_key)).unwrap(); )); } diff --git a/src/client.rs b/src/client.rs index a7f45011..247954c2 100644 --- a/src/client.rs +++ b/src/client.rs @@ -20,7 +20,7 @@ use crate::{ pub struct Client { pub(crate) host: String, pub(crate) api_key: Option, - pub http_client: Http, + pub(crate) http_client: Http, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -28,8 +28,7 @@ pub struct SwapIndexes { pub indexes: (String, String), } -#[cfg(feature = "isahc")] -#[cfg(not(target_arch = "wasm32"))] +#[cfg(feature = "reqwest")] impl Client { /// Create a client using the specified server. /// @@ -45,42 +44,20 @@ impl Client { /// let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// - /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); - /// ``` - pub fn new(host: impl Into, api_key: Option>) -> Client { - Client { - host: host.into(), - api_key: api_key.map(|api_key| api_key.into()), - http_client: IsahcClient, - } - } -} - -#[cfg(target_arch = "wasm32")] -impl Client { - /// Create a client using the specified server. - /// Don't put a '/' at the end of the host. - /// In production mode, see [the documentation about authentication](https://docs.meilisearch.com/reference/features/authentication.html#authentication). - /// # Example - /// - /// ``` - /// # use meilisearch_sdk::{client::*, indexes::*}; - /// # - /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); - /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # - /// // create the client - /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// ``` pub fn new( host: impl Into, api_key: Option>, - ) -> Client { - Client { + ) -> Result { + let api_key = api_key.map(|key| key.into()); + let http_client = crate::reqwest::ReqwestClient::new(api_key.as_deref())?; + + Ok(Client { host: host.into(), - api_key: api_key.map(|key| key.into()), - http_client: WebSysClient::new(), - } + api_key, + http_client, + }) } } @@ -122,10 +99,8 @@ impl Client { body: &MultiSearchQuery<'_, '_, Http>, ) -> Result, Error> { self.http_client - .clone() .request::<(), &MultiSearchQuery, MultiSearchResponse>( &format!("{}/multi-search", &self.host), - self.get_api_key(), Method::Post { body, query: () }, 200, ) @@ -149,8 +124,8 @@ impl Client { /// description: String, /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut movies = client.index("search"); /// # // add some documents /// # movies.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); @@ -186,7 +161,7 @@ impl Client { /// ``` /// # use meilisearch_sdk::{client::*}; /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// let client = Client::new("http://doggo.dog", Some(MEILISEARCH_API_KEY)); + /// let client = Client::new("http://doggo.dog", Some(MEILISEARCH_API_KEY)).unwrap(); /// /// assert_eq!(client.get_host(), "http://doggo.dog"); /// ``` @@ -202,7 +177,7 @@ impl Client { /// ``` /// # use meilisearch_sdk::{client::*}; /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); - /// let client = Client::new(MEILISEARCH_URL, Some("doggo")); + /// let client = Client::new(MEILISEARCH_URL, Some("doggo")).unwrap(); /// /// assert_eq!(client.get_api_key(), Some("doggo")); /// ``` @@ -221,8 +196,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let indexes: IndexesResults = client.list_all_indexes().await.unwrap(); /// /// let indexes: IndexesResults = client.list_all_indexes().await.unwrap(); @@ -245,8 +220,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut query = IndexesQuery::new(&client); /// query.with_limit(1); /// @@ -275,19 +250,18 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let json_indexes = client.list_all_indexes_raw().await.unwrap(); /// /// println!("{:?}", json_indexes); /// # }); /// ``` pub async fn list_all_indexes_raw(&self) -> Result { - let http_client = self.http_client.clone(); - let json_indexes = http_client + let json_indexes = self + .http_client .request::<(), (), Value>( &format!("{}/indexes", self.host), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -306,8 +280,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut query = IndexesQuery::new(&client); /// query.with_limit(1); /// @@ -320,11 +294,10 @@ impl Client { &self, indexes_query: &IndexesQuery<'_, Http>, ) -> Result { - let http_client = self.http_client.clone(); - let json_indexes = http_client + let json_indexes = self + .http_client .request::<&IndexesQuery, (), Value>( &format!("{}/indexes", self.host), - self.get_api_key(), Method::Get { query: indexes_query, }, @@ -345,8 +318,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("get_index", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// let index = client.get_index("get_index").await.unwrap(); /// @@ -372,8 +345,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("get_raw_index", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// let raw_index = client.get_raw_index("get_raw_index").await.unwrap(); /// @@ -383,10 +356,8 @@ impl Client { /// ``` pub async fn get_raw_index(&self, uid: impl AsRef) -> Result { self.http_client - .clone() .request::<(), (), Value>( &format!("{}/indexes/{}", self.host, uid.as_ref()), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -411,8 +382,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// // Create a new index called movies and access it /// let task = client.create_index("create_index", None).await.unwrap(); /// @@ -432,10 +403,8 @@ impl Client { primary_key: Option<&str>, ) -> Result { self.http_client - .clone() .request::<(), Value, TaskInfo>( &format!("{}/indexes", self.host), - self.get_api_key(), Method::Post { query: (), body: json!({ @@ -453,10 +422,8 @@ impl Client { /// To delete an [Index], use the [`Index::delete`] method. pub async fn delete_index(&self, uid: impl AsRef) -> Result { self.http_client - .clone() .request::<(), (), TaskInfo>( &format!("{}/indexes/{}", self.host, uid.as_ref()), - self.get_api_key(), Method::Delete { query: () }, 202, ) @@ -499,8 +466,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let task_index_1 = client.create_index("swap_index_1", None).await.unwrap(); /// let task_index_2 = client.create_index("swap_index_2", None).await.unwrap(); /// @@ -526,10 +493,8 @@ impl Client { indexes: impl IntoIterator, ) -> Result { self.http_client - .clone() .request::<(), Vec<&SwapIndexes>, TaskInfo>( &format!("{}/swap-indexes", self.host), - self.get_api_key(), Method::Post { query: (), body: indexes.into_iter().collect(), @@ -549,17 +514,15 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let stats = client.get_stats().await.unwrap(); /// # }); /// ``` pub async fn get_stats(&self) -> Result { self.http_client - .clone() .request::<(), (), ClientStats>( &format!("{}/stats", self.host), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -576,8 +539,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let health = client.health().await.unwrap(); /// /// assert_eq!(health.status, "available"); @@ -585,10 +548,8 @@ impl Client { /// ``` pub async fn health(&self) -> Result { self.http_client - .clone() .request::<(), (), Health>( &format!("{}/health", self.host), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -605,8 +566,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let health = client.is_healthy().await; /// /// assert_eq!(health, true); @@ -632,8 +593,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut query = KeysQuery::new(); /// query.with_limit(1); /// @@ -643,11 +604,10 @@ impl Client { /// # }); /// ``` pub async fn get_keys_with(&self, keys_query: &KeysQuery) -> Result { - let http_client = self.http_client.clone(); - let keys = http_client + let keys = self + .http_client .request::<&KeysQuery, (), KeysResults>( &format!("{}/keys", self.host), - self.get_api_key(), Method::Get { query: keys_query }, 200, ) @@ -668,19 +628,18 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let keys = client.get_keys().await.unwrap(); /// /// assert_eq!(keys.limit, 20); /// # }); /// ``` pub async fn get_keys(&self) -> Result { - let http_client = self.http_client.clone(); - let keys = http_client + let keys = self + .http_client .request::<(), (), KeysResults>( &format!("{}/keys", self.host), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -701,22 +660,20 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let key = client.get_keys().await.unwrap().results.into_iter() /// # .find(|k| k.name.as_ref().map_or(false, |name| name.starts_with("Default Search API Key"))) - /// # .unwrap(); - /// let key = client.get_key(key).await.unwrap(); + /// # .expect("No default search key"); + /// let key = client.get_key(key).await.expect("Invalid key"); /// /// assert_eq!(key.name, Some("Default Search API Key".to_string())); /// # }); /// ``` pub async fn get_key(&self, key: impl AsRef) -> Result { self.http_client - .clone() .request::<(), (), Key>( &format!("{}/keys/{}", self.host, key.as_ref()), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -735,8 +692,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let key = KeyBuilder::new(); /// let key = client.create_key(key).await.unwrap(); /// let inner_key = key.key.clone(); @@ -750,10 +707,8 @@ impl Client { /// ``` pub async fn delete_key(&self, key: impl AsRef) -> Result<(), Error> { self.http_client - .clone() .request::<(), (), ()>( &format!("{}/keys/{}", self.host, key.as_ref()), - self.get_api_key(), Method::Delete { query: () }, 204, ) @@ -772,8 +727,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let name = "create_key".to_string(); /// let mut key = KeyBuilder::new(); /// key.with_name(&name); @@ -786,10 +741,8 @@ impl Client { /// ``` pub async fn create_key(&self, key: impl AsRef) -> Result { self.http_client - .clone() .request::<(), &KeyBuilder, Key>( &format!("{}/keys", self.host), - self.get_api_key(), Method::Post { query: (), body: key.as_ref(), @@ -811,8 +764,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let new_key = KeyBuilder::new(); /// let mut new_key = client.create_key(new_key).await.unwrap(); /// let mut key_update = KeyUpdater::new(new_key); @@ -828,10 +781,8 @@ impl Client { /// ``` pub async fn update_key(&self, key: impl AsRef) -> Result { self.http_client - .clone() .request::<(), &KeyUpdater, Key>( &format!("{}/keys/{}", self.host, key.as_ref().key), - self.get_api_key(), Method::Patch { body: key.as_ref(), query: (), @@ -851,17 +802,15 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let version = client.get_version().await.unwrap(); /// # }); /// ``` pub async fn get_version(&self) -> Result { self.http_client - .clone() .request::<(), (), Version>( &format!("{}/version", self.host), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -896,8 +845,8 @@ impl Client { /// # } /// # /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("movies_client_wait_for_task"); /// /// let task = movies.add_documents(&[ @@ -952,8 +901,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("movies_get_task", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// let task = index.delete_all_documents().await.unwrap(); /// @@ -963,10 +912,8 @@ impl Client { /// ``` pub async fn get_task(&self, task_id: impl AsRef) -> Result { self.http_client - .clone() .request::<(), (), Task>( &format!("{}/tasks/{}", self.host, task_id.as_ref()), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -983,8 +930,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut query = TasksSearchQuery::new(&client); /// query.with_index_uids(["get_tasks_with"]); /// @@ -995,11 +942,10 @@ impl Client { &self, tasks_query: &TasksSearchQuery<'_, Http>, ) -> Result { - let http_client = self.http_client.clone(); - let tasks = http_client + let tasks = self + .http_client .request::<&TasksSearchQuery, (), TasksResults>( &format!("{}/tasks", self.host), - self.get_api_key(), Method::Get { query: tasks_query }, 200, ) @@ -1018,8 +964,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut query = TasksCancelQuery::new(&client); /// query.with_index_uids(["movies"]); /// @@ -1030,11 +976,10 @@ impl Client { &self, filters: &TasksCancelQuery<'_, Http>, ) -> Result { - let http_client = self.http_client.clone(); - let tasks = http_client + let tasks = self + .http_client .request::<&TasksCancelQuery, (), TaskInfo>( &format!("{}/tasks/cancel", self.host), - self.get_api_key(), Method::Post { query: filters, body: (), @@ -1056,8 +1001,8 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut query = TasksDeleteQuery::new(&client); /// query.with_index_uids(["movies"]); /// @@ -1068,11 +1013,10 @@ impl Client { &self, filters: &TasksDeleteQuery<'_, Http>, ) -> Result { - let http_client = self.http_client.clone(); - let tasks = http_client + let tasks = self + .http_client .request::<&TasksDeleteQuery, (), TaskInfo>( &format!("{}/tasks", self.host), - self.get_api_key(), Method::Delete { query: filters }, 200, ) @@ -1091,19 +1035,18 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let tasks = client.get_tasks().await.unwrap(); /// /// assert!(tasks.results.len() > 0); /// # }); /// ``` pub async fn get_tasks(&self) -> Result { - let http_client = self.http_client.clone(); - let tasks = http_client + let tasks = self + .http_client .request::<(), (), TasksResults>( &format!("{}/tasks", self.host), - self.get_api_key(), Method::Get { query: () }, 200, ) @@ -1122,12 +1065,12 @@ impl Client { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let api_key_uid = "76cf8b87-fd12-4688-ad34-260d930ca4f4".to_string(); /// let token = client.generate_tenant_token(api_key_uid, serde_json::json!(["*"]), None, None).unwrap(); /// - /// let client = Client::new(MEILISEARCH_URL, Some(token)); + /// let client = Client::new(MEILISEARCH_URL, Some(token)).unwrap(); /// # }); /// ``` #[cfg(not(target_arch = "wasm32"))] @@ -1202,7 +1145,7 @@ mod tests { use meilisearch_test_macro::meilisearch_test; - use crate::{client::*, key::Action}; + use crate::{client::*, key::Action, reqwest::qualified_version}; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct Document { @@ -1264,7 +1207,7 @@ mod tests { let path = "/hello"; let address = &format!("{mock_server_url}{path}"); let user_agent = &*qualified_version(); - let client = Client::new(mock_server_url, None::); + let client = Client::new(mock_server_url, None::).unwrap(); let assertions = vec![ ( @@ -1272,12 +1215,9 @@ mod tests { .match_header("User-Agent", user_agent) .create_async() .await, - client.http_client.request::<(), (), ()>( - address, - None, - Method::Get { query: () }, - 200, - ), + client + .http_client + .request::<(), (), ()>(address, Method::Get { query: () }, 200), ), ( s.mock("POST", path) @@ -1286,7 +1226,6 @@ mod tests { .await, client.http_client.request::<(), (), ()>( address, - None, Method::Post { query: (), body: {}, @@ -1301,7 +1240,6 @@ mod tests { .await, client.http_client.request::<(), (), ()>( address, - None, Method::Delete { query: () }, 200, ), @@ -1313,7 +1251,6 @@ mod tests { .await, client.http_client.request::<(), (), ()>( address, - None, Method::Put { query: (), body: (), @@ -1328,7 +1265,6 @@ mod tests { .await, client.http_client.request::<(), (), ()>( address, - None, Method::Patch { query: (), body: (), @@ -1383,17 +1319,10 @@ mod tests { } #[meilisearch_test] - async fn test_error_delete_key(mut client: Client, name: String) { + async fn test_error_delete_key(client: Client, name: String) { // ==> accessing a key that does not exist let error = client.delete_key("invalid_key").await.unwrap_err(); - assert!(matches!( - error, - Error::Meilisearch(MeilisearchError { - error_code: ErrorCode::ApiKeyNotFound, - error_type: ErrorType::InvalidRequest, - .. - }) - )); + insta::assert_snapshot!(error, @"Meilisearch invalid_request: api_key_not_found: API key `invalid_key` not found.. https://docs.meilisearch.com/errors#api_key_not_found"); // ==> executing the action without enough right let mut key = KeyBuilder::new(); @@ -1401,10 +1330,12 @@ mod tests { key.with_name(&name); let key = client.create_key(key).await.unwrap(); let master_key = client.api_key.clone(); - // this key has no right - client.api_key = Some(key.key.clone()); + + // create a new client with no right + let client = Client::new(client.host, Some(key.key.clone())).unwrap(); // with a wrong key let error = client.delete_key("invalid_key").await.unwrap_err(); + insta::assert_snapshot!(error, @"Meilisearch auth: invalid_api_key: The provided API key is invalid.. https://docs.meilisearch.com/errors#invalid_api_key"); assert!(matches!( error, Error::Meilisearch(MeilisearchError { @@ -1415,6 +1346,7 @@ mod tests { )); // with a good key let error = client.delete_key(&key.key).await.unwrap_err(); + insta::assert_snapshot!(error, @"Meilisearch auth: invalid_api_key: The provided API key is invalid.. https://docs.meilisearch.com/errors#invalid_api_key"); assert!(matches!( error, Error::Meilisearch(MeilisearchError { @@ -1425,7 +1357,7 @@ mod tests { )); // cleanup - client.api_key = master_key; + let client = Client::new(client.host, master_key).unwrap(); client.delete_key(key).await.unwrap(); } @@ -1453,7 +1385,7 @@ mod tests { } #[meilisearch_test] - async fn test_error_create_key(mut client: Client, name: String) { + async fn test_error_create_key(client: Client, name: String) { // ==> Invalid index name /* TODO: uncomment once meilisearch fix this bug: https://github.com/meilisearch/meilisearch/issues/2158 let mut key = KeyBuilder::new(); @@ -1476,7 +1408,7 @@ mod tests { // backup the master key for cleanup at the end of the test let master_client = client.clone(); - client.api_key = Some(no_right_key.key.clone()); + let client = Client::new(&master_client.host, Some(no_right_key.key.clone())).unwrap(); let mut key = KeyBuilder::new(); key.with_name(format!("{name}_2")); diff --git a/src/documents.rs b/src/documents.rs index 50713aef..17e2e610 100644 --- a/src/documents.rs +++ b/src/documents.rs @@ -55,15 +55,15 @@ use crate::tasks::Task; use crate::{errors::Error, indexes::Index}; #[async_trait(?Send)] -pub trait IndexConfig { +pub trait IndexConfig { const INDEX_STR: &'static str; #[must_use] - fn index(client: &Client) -> Index { + fn index(client: &Client) -> Index { client.index(Self::INDEX_STR) } fn generate_settings() -> Settings; - async fn generate_index(client: &Client) -> Result, Task>; + async fn generate_index(client: &Client) -> Result, Task>; } #[derive(Debug, Clone, Deserialize)] @@ -103,7 +103,7 @@ impl<'a, Http: HttpClient> DocumentQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let index = client.index("document_query_with_fields"); /// let mut document_query = DocumentQuery::new(&index); /// @@ -128,8 +128,8 @@ impl<'a, Http: HttpClient> DocumentQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); - /// # futures::executor::block_on(async move { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// #[derive(Debug, Serialize, Deserialize, PartialEq)] /// struct MyObject { /// id: String, @@ -220,7 +220,7 @@ impl<'a, Http: HttpClient> DocumentsQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let index = client.index("my_index"); /// /// let mut documents_query = DocumentsQuery::new(&index).with_offset(1); @@ -240,7 +240,7 @@ impl<'a, Http: HttpClient> DocumentsQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let index = client.index("my_index"); /// /// let mut documents_query = DocumentsQuery::new(&index); @@ -262,7 +262,7 @@ impl<'a, Http: HttpClient> DocumentsQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let index = client.index("my_index"); /// /// let mut documents_query = DocumentsQuery::new(&index); @@ -293,8 +293,8 @@ impl<'a, Http: HttpClient> DocumentsQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); - /// # futures::executor::block_on(async move { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # let index = client.create_index("documents_query_execute", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// #[derive(Debug, Serialize, Deserialize, PartialEq)] /// struct MyObject { @@ -355,7 +355,7 @@ impl<'a, Http: HttpClient> DocumentDeletionQuery<'a, Http> { #[cfg(test)] mod tests { use super::*; - use crate::{client::Client, errors::*, indexes::*, request::IsahcClient}; + use crate::{client::Client, errors::*, indexes::*}; use meilisearch_test_macro::meilisearch_test; use serde::{Deserialize, Serialize}; @@ -367,10 +367,7 @@ mod tests { #[allow(unused)] #[derive(IndexConfig)] - struct MovieClips - where - IsahcClient: HttpClient, - { + struct MovieClips { #[index_config(primary_key)] movie_id: u64, #[index_config(distinct)] @@ -387,10 +384,7 @@ mod tests { #[allow(unused)] #[derive(IndexConfig)] - struct VideoClips - where - IsahcClient: HttpClient, - { + struct VideoClips { video_id: u64, } @@ -547,7 +541,7 @@ mod tests { #[meilisearch_test] async fn test_get_documents_with_error_hint() -> Result<(), Error> { let meilisearch_url = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); - let client = Client::new(format!("{meilisearch_url}/hello"), Some("masterKey")); + let client = Client::new(format!("{meilisearch_url}/hello"), Some("masterKey")).unwrap(); let index = client.index("test_get_documents_with_filter_wrong_ms_version"); let documents = DocumentsQuery::new(&index) diff --git a/src/dumps.rs b/src/dumps.rs index 7dfcd987..f0d23559 100644 --- a/src/dumps.rs +++ b/src/dumps.rs @@ -19,12 +19,12 @@ //! # use meilisearch_sdk::{client::*, errors::*, dumps::*, dumps::*, task_info::*, tasks::*}; //! # use futures_await_test::async_test; //! # use std::{thread::sleep, time::Duration}; -//! # futures::executor::block_on(async move { +//! # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { //! # //! # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); //! # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); //! # -//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); //! //! // Create a dump //! let task_info = client.create_dump().await.unwrap(); @@ -54,12 +54,12 @@ impl Client { /// # use meilisearch_sdk::{client::*, errors::*, dumps::*, dumps::*, task_info::*, tasks::*}; /// # use futures_await_test::async_test; /// # use std::{thread::sleep, time::Duration}; - /// # futures::executor::block_on(async move { + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # /// let task_info = client.create_dump().await.unwrap(); /// @@ -74,10 +74,8 @@ impl Client { /// ``` pub async fn create_dump(&self) -> Result { self.http_client - .clone() .request::<(), (), TaskInfo>( &format!("{}/dumps", self.host), - self.get_api_key(), Method::Post { query: (), body: (), diff --git a/src/errors.rs b/src/errors.rs index 23ac5dbd..cdaa3815 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -11,12 +11,9 @@ pub enum Error { /// Also check out: #[error(transparent)] Meilisearch(#[from] MeilisearchError), + #[error(transparent)] MeilisearchCommunication(#[from] MeilisearchCommunicationError), - /// There is no Meilisearch server listening on the [specified host] - /// (../client/struct.Client.html#method.new). - #[error("The Meilisearch server can't be reached.")] - UnreachableServer, /// The Meilisearch server returned an invalid JSON for a request. #[error("Error parsing response JSON: {}", .0)] ParseError(#[from] serde_json::Error), @@ -42,30 +39,30 @@ pub enum Error { TenantTokensExpiredSignature, /// When jsonwebtoken cannot generate the token successfully. + #[cfg(not(target_arch = "wasm32"))] #[error("Impossible to generate the token, jsonwebtoken encountered an error: {}", .0)] InvalidTenantToken(#[from] jsonwebtoken::errors::Error), /// The http client encountered an error. - #[cfg(feature = "isahc")] - #[cfg(not(target_arch = "wasm32"))] - #[error("HTTP request failed: {}", .0)] - HttpError(isahc::Error), - - /// The http client encountered an error. - #[cfg(target_arch = "wasm32")] + #[cfg(feature = "reqwest")] #[error("HTTP request failed: {}", .0)] - HttpError(String), + HttpError(#[from] reqwest::Error), // The library formatting the query parameters encountered an error. #[error("Internal Error: could not parse the query parameters: {}", .0)] Yaup(#[from] yaup::Error), + // The library validating the format of an uuid. #[cfg(not(target_arch = "wasm32"))] #[error("The uid of the token has bit an uuid4 format: {}", .0)] Uuid(#[from] uuid::Error), + // Error thrown in case the version of the Uuid is not v4. #[error("The uid provided to the token is not of version uuidv4")] InvalidUuid4Version, + + #[error(transparent)] + Other(Box), } #[derive(Debug, Clone, Deserialize, Error)] @@ -277,27 +274,16 @@ impl std::fmt::Display for ErrorCode { } } -#[cfg(feature = "isahc")] -#[cfg(not(target_arch = "wasm32"))] -impl From for Error { - fn from(error: isahc::Error) -> Error { - if error.kind() == isahc::error::ErrorKind::ConnectionFailed { - Error::UnreachableServer - } else { - Error::HttpError(error) - } - } -} - #[cfg(test)] mod test { use super::*; use jsonwebtoken::errors::ErrorKind::InvalidToken; + use meilisearch_test_macro::meilisearch_test; use uuid::Uuid; - #[test] - fn test_meilisearch_error() { + #[meilisearch_test] + async fn test_meilisearch_error() { let error: MeilisearchError = serde_json::from_str( r#" { @@ -329,8 +315,8 @@ mod test { assert_eq!(error.error_type, ErrorType::Unknown); } - #[test] - fn test_error_message_parsing() { + #[meilisearch_test] + async fn test_error_message_parsing() { let error: MeilisearchError = serde_json::from_str( r#" { @@ -366,12 +352,6 @@ mod test { "MeilisearchCommunicationError: The server responded with a 404.\nurl: http://localhost:7700/something" ); - let error = Error::UnreachableServer; - assert_eq!( - error.to_string(), - "The Meilisearch server can't be reached." - ); - let error = Error::Timeout; assert_eq!(error.to_string(), "A task did not succeed in time."); @@ -411,10 +391,19 @@ mod test { "Error parsing response JSON: invalid type: map, expected a string at line 2 column 8" ); - let error = Error::HttpError(isahc::post("test_url", "test_body").unwrap_err()); + let error = Error::HttpError( + reqwest::Client::new() + .execute(reqwest::Request::new( + reqwest::Method::POST, + // there will never be a `meilisearch.gouv.fr` addr since these domain name are controlled by the state of france + reqwest::Url::parse("https://meilisearch.gouv.fr").unwrap(), + )) + .await + .unwrap_err(), + ); assert_eq!( error.to_string(), - "HTTP request failed: failed to resolve host name" + "HTTP request failed: error sending request for url (https://meilisearch.gouv.fr/)" ); let error = Error::InvalidTenantToken(jsonwebtoken::errors::Error::from(InvalidToken)); diff --git a/src/features.rs b/src/features.rs index a1784418..3001beb4 100644 --- a/src/features.rs +++ b/src/features.rs @@ -22,7 +22,7 @@ pub struct ExperimentalFeaturesResult { /// # use meilisearch_sdk::{client::Client, features::ExperimentalFeatures}; /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut features = ExperimentalFeatures::new(&client); /// features.set_vector_store(true); /// ``` @@ -57,8 +57,8 @@ impl<'a, Http: HttpClient> ExperimentalFeatures<'a, Http> { /// # use meilisearch_sdk::{client::Client, features::ExperimentalFeatures}; /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); - /// futures::executor::block_on(async move { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); + /// tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// let features = ExperimentalFeatures::new(&client); /// features.get().await.unwrap(); /// }); @@ -66,10 +66,8 @@ impl<'a, Http: HttpClient> ExperimentalFeatures<'a, Http> { pub async fn get(&self) -> Result { self.client .http_client - .clone() .request::<(), (), ExperimentalFeaturesResult>( &format!("{}/experimental-features", self.client.host), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -84,8 +82,8 @@ impl<'a, Http: HttpClient> ExperimentalFeatures<'a, Http> { /// # use meilisearch_sdk::{client::Client, features::ExperimentalFeatures}; /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); - /// futures::executor::block_on(async move { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); + /// tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// let mut features = ExperimentalFeatures::new(&client); /// features.set_vector_store(true); /// features.update().await.unwrap(); @@ -94,10 +92,8 @@ impl<'a, Http: HttpClient> ExperimentalFeatures<'a, Http> { pub async fn update(&self) -> Result { self.client .http_client - .clone() .request::<(), &Self, ExperimentalFeaturesResult>( &format!("{}/experimental-features", self.client.host), - self.client.get_api_key(), Method::Patch { query: (), body: self, diff --git a/src/indexes.rs b/src/indexes.rs index 952f4a99..4d6b0e79 100644 --- a/src/indexes.rs +++ b/src/indexes.rs @@ -24,8 +24,8 @@ use time::OffsetDateTime; /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # -/// # futures::executor::block_on(async move { -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// /// // get the index called movies or create it if it does not exist /// let movies = client @@ -52,8 +52,8 @@ use time::OffsetDateTime; /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # -/// # futures::executor::block_on(async move { -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// /// // Meilisearch would be able to create the index if it does not exist during: /// // - the documents addition (add and update routes) @@ -123,8 +123,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let mut index = client /// # .create_index("index_update", None) /// # .await @@ -170,8 +170,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("delete", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// /// // get the index named "movies" and delete it @@ -184,10 +184,8 @@ impl Index { pub async fn delete(self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!("{}/indexes/{}", self.client.host, self.uid), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -212,8 +210,8 @@ impl Index { /// name: String, /// description: String, /// } - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("execute_query"); /// /// // add some documents @@ -232,10 +230,8 @@ impl Index { ) -> Result, Error> { self.client .http_client - .clone() .request::<(), &SearchQuery, SearchResults>( &format!("{}/indexes/{}/search", self.client.host, self.uid), - self.client.get_api_key(), Method::Post { body, query: () }, 200, ) @@ -261,8 +257,8 @@ impl Index { /// description: String, /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut movies = client.index("search"); /// # // add some documents /// # movies.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")},Movie{name:String::from("Unknown"), description:String::from("Unknown")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); @@ -302,8 +298,8 @@ impl Index { /// description: String /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("get_document"); /// # movies.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// @@ -327,13 +323,7 @@ impl Index { ); self.client .http_client - .clone() - .request::<(), (), T>( - &url, - self.client.get_api_key(), - Method::Get { query: () }, - 200, - ) + .request::<(), (), T>(&url, Method::Get { query: () }, 200) .await } @@ -348,8 +338,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); - /// # futures::executor::block_on(async move { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// #[derive(Debug, Serialize, Deserialize, PartialEq)] /// struct MyObject { /// id: String, @@ -385,10 +375,8 @@ impl Index { ); self.client .http_client - .clone() .request::<&DocumentQuery, (), T>( &url, - self.client.get_api_key(), Method::Get { query: document_query, }, @@ -414,8 +402,8 @@ impl Index { /// description: String, /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("get_documents"); /// # movie_index.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// @@ -432,13 +420,7 @@ impl Index { let url = format!("{}/indexes/{}/documents", self.client.host, self.uid); self.client .http_client - .clone() - .request::<(), (), DocumentsResults>( - &url, - self.client.get_api_key(), - Method::Get { query: () }, - 200, - ) + .request::<(), (), DocumentsResults>(&url, Method::Get { query: () }, 200) .await } @@ -463,8 +445,8 @@ impl Index { /// struct ReturnedMovie { /// name: String, /// } - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// /// let movie_index = client.index("get_documents_with"); /// # movie_index.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); @@ -488,10 +470,8 @@ impl Index { return self .client .http_client - .clone() .request::<(), &DocumentsQuery, DocumentsResults>( &url, - self.client.get_api_key(), Method::Post { body: documents_query, query: (), @@ -523,10 +503,8 @@ impl Index { let url = format!("{}/indexes/{}/documents", self.client.host, self.uid); self.client .http_client - .clone() .request::<&DocumentsQuery, (), DocumentsResults>( &url, - self.client.get_api_key(), Method::Get { query: documents_query, }, @@ -561,8 +539,8 @@ impl Index { /// description: String, /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("add_or_replace"); /// /// let task = movie_index.add_or_replace(&[ @@ -603,10 +581,8 @@ impl Index { }; self.client .http_client - .clone() .request::<(), &[T], TaskInfo>( &url, - self.client.get_api_key(), Method::Post { query: (), body: documents, @@ -635,8 +611,8 @@ impl Index { /// # /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("add_or_replace_unchecked_payload"); /// /// let task = movie_index.add_or_replace_unchecked_payload( @@ -653,7 +629,6 @@ impl Index { /// # movie_index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// # }); /// ``` - #[cfg(not(target_arch = "wasm32"))] pub async fn add_or_replace_unchecked_payload< T: futures_io::AsyncRead + Send + Sync + 'static, >( @@ -670,11 +645,10 @@ impl Index { } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; - let http_clint = self.client.http_client.clone(); - http_clint + self.client + .http_client .stream_request::<(), T, TaskInfo>( &url, - self.client.get_api_key(), Method::Post { query: (), body: payload, @@ -713,8 +687,8 @@ impl Index { /// # /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("update_documents_ndjson"); /// /// let task = movie_index.update_documents_ndjson( @@ -759,8 +733,8 @@ impl Index { /// # /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("add_documents_ndjson"); /// /// let task = movie_index.add_documents_ndjson( @@ -805,8 +779,8 @@ impl Index { /// # /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("update_documents_csv"); /// /// let task = movie_index.update_documents_csv( @@ -850,8 +824,8 @@ impl Index { /// # /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("add_documents_csv"); /// /// let task = movie_index.add_documents_csv( @@ -900,8 +874,8 @@ impl Index { /// description: String, /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("add_or_update"); /// /// let task = movie_index.add_or_update(&[ @@ -943,11 +917,10 @@ impl Index { } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; - let client = self.client.http_client.clone(); - client + self.client + .http_client .request::<(), &[T], TaskInfo>( &url, - self.client.get_api_key(), Method::Put { query: (), body: documents, @@ -976,8 +949,8 @@ impl Index { /// # /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("add_or_replace_unchecked_payload"); /// /// let task = movie_index.add_or_update_unchecked_payload( @@ -1012,11 +985,10 @@ impl Index { } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; - let http_client = self.client.http_client.clone(); - http_client + self.client + .http_client .stream_request::<(), T, TaskInfo>( &url, - self.client.get_api_key(), Method::Put { query: (), body: payload, @@ -1045,9 +1017,9 @@ impl Index { /// # } /// # /// # - /// # futures::executor::block_on(async move { + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("delete_all_documents"); /// # /// # movie_index.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); @@ -1066,10 +1038,8 @@ impl Index { pub async fn delete_all_documents(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!("{}/indexes/{}/documents", self.client.host, self.uid), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1094,9 +1064,9 @@ impl Index { /// # } /// # /// # - /// # futures::executor::block_on(async move { + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut movies = client.index("delete_document"); /// # movies.add_or_replace(&[Movie{name:String::from("Interstellar"), description:String::from("Interstellar chronicles the adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.")}], Some("name")).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// // add a document with id = Interstellar @@ -1112,13 +1082,11 @@ impl Index { pub async fn delete_document(&self, uid: T) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/documents/{}", self.client.host, self.uid, uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1143,9 +1111,9 @@ impl Index { /// # } /// # /// # - /// # futures::executor::block_on(async move { + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("delete_documents"); /// # /// # // add some documents @@ -1167,13 +1135,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), &[T], TaskInfo>( &format!( "{}/indexes/{}/documents/delete-batch", self.client.host, self.uid ), - self.client.get_api_key(), Method::Post { query: (), body: uids, @@ -1201,9 +1167,9 @@ impl Index { /// # } /// # /// # - /// # futures::executor::block_on(async move { + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let index = client.index("delete_documents_with"); /// # /// # index.set_filterable_attributes(["id"]); @@ -1228,10 +1194,8 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), &DocumentDeletionQuery, TaskInfo>( &format!("{}/indexes/{}/documents/delete", self.client.host, self.uid), - self.client.get_api_key(), Method::Post { query: (), body: query, @@ -1263,8 +1227,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("fetch_info", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// let mut idx = client.index("fetch_info"); /// idx.fetch_info().await.unwrap(); @@ -1289,9 +1253,9 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # // create the client - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut index = client.create_index("get_primary_key", Some("id")) /// .await /// .unwrap() @@ -1332,8 +1296,8 @@ impl Index { /// # } /// # /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("get_task"); /// /// let task = movies.add_documents(&[ @@ -1358,10 +1322,8 @@ impl Index { pub async fn get_task(&self, uid: impl AsRef) -> Result { self.client .http_client - .clone() .request::<(), (), Task>( &format!("{}/tasks/{}", self.client.host, uid.as_ref()), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -1379,8 +1341,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("get_tasks", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// let tasks = index.get_tasks().await.unwrap(); /// @@ -1406,8 +1368,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("get_tasks_with", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// let mut query = TasksSearchQuery::new(&client); /// query.with_index_uids(["none_existant"]); @@ -1438,8 +1400,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.create_index("get_stats", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// let stats = index.get_stats().await.unwrap(); /// @@ -1450,10 +1412,8 @@ impl Index { pub async fn get_stats(&self) -> Result { self.client .http_client - .clone() .request::<(), (), IndexStats>( &format!("{}/indexes/{}/stats", self.client.host, self.uid), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -1487,8 +1447,8 @@ impl Index { /// # } /// # /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("movies_index_wait_for_task"); /// /// let task = movies.add_documents(&[ @@ -1533,8 +1493,8 @@ impl Index { /// description: String, /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("add_documents_in_batches"); /// /// let tasks = movie_index.add_documents_in_batches(&[ @@ -1599,8 +1559,8 @@ impl Index { /// description: String, /// } /// - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movie_index = client.index("update_documents_in_batches"); /// /// let tasks = movie_index.add_documents_in_batches(&[ @@ -1680,8 +1640,8 @@ impl AsRef for Index { /// # use meilisearch_sdk::{client::*, indexes::*, task_info::*, tasks::{Task, SucceededTask}}; /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); -/// # futures::executor::block_on(async move { -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("index_updater", None) /// # .await @@ -1735,8 +1695,8 @@ impl<'a, Http: HttpClient> IndexUpdater<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("index_updater_with_primary_key", None) /// # .await @@ -1780,8 +1740,8 @@ impl<'a, Http: HttpClient> IndexUpdater<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("index_updater_execute", None) /// # .await @@ -1810,10 +1770,8 @@ impl<'a, Http: HttpClient> IndexUpdater<'a, Http> { pub async fn execute(&'a self) -> Result { self.client .http_client - .clone() .request::<(), &IndexUpdater, TaskInfo>( &format!("{}/indexes/{}", self.client.host, self.uid), - self.client.get_api_key(), Method::Patch { query: (), body: self, @@ -1854,8 +1812,8 @@ pub struct IndexStats { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # -/// # futures::executor::block_on(async move { -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("index_query_builder", None) /// # .await @@ -1920,8 +1878,8 @@ impl<'a, Http: HttpClient> IndexesQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("index_query_with_offset", None) /// # .await @@ -1955,8 +1913,8 @@ impl<'a, Http: HttpClient> IndexesQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("index_query_with_limit", None) /// # .await @@ -1989,8 +1947,8 @@ impl<'a, Http: HttpClient> IndexesQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("index_query_with_execute", None) /// # .await diff --git a/src/key.rs b/src/key.rs index 3c8f51a7..bda7eb26 100644 --- a/src/key.rs +++ b/src/key.rs @@ -38,8 +38,8 @@ impl Key { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let description = "My not so little lovely test key".to_string(); /// let mut key = KeyBuilder::new() /// .with_action(Action::DocumentsAdd) @@ -66,8 +66,8 @@ impl Key { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let name = "lovely key".to_string(); /// let mut key = KeyBuilder::new() /// .with_action(Action::DocumentsAdd) @@ -97,8 +97,8 @@ impl Key { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut key = KeyBuilder::new() /// .execute(&client) /// .await @@ -137,8 +137,8 @@ impl Key { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut key = KeyBuilder::new() /// .execute(&client).await.unwrap(); /// @@ -190,8 +190,8 @@ impl KeyUpdater { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut new_key = KeyBuilder::new() /// .execute(&client) /// .await @@ -223,8 +223,8 @@ impl KeyUpdater { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut new_key = KeyBuilder::new() /// .execute(&client) /// .await @@ -256,8 +256,8 @@ impl KeyUpdater { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let description = "My little lovely test key".to_string(); /// let key = KeyBuilder::new() /// .execute(&client).await.unwrap(); @@ -333,8 +333,8 @@ impl KeysQuery { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut keys = KeysQuery::new() /// .with_offset(1) /// .execute(&client).await.unwrap(); @@ -357,8 +357,8 @@ impl KeysQuery { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut keys = KeysQuery::new() /// .with_limit(1) /// .execute(&client).await.unwrap(); @@ -381,8 +381,8 @@ impl KeysQuery { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut keys = KeysQuery::new() /// .with_limit(1) /// .execute(&client).await.unwrap(); @@ -410,8 +410,8 @@ impl KeysQuery { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # -/// # futures::executor::block_on(async move { -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let description = "My little lovely test key".to_string(); /// let key = KeyBuilder::new() /// .with_description(&description) @@ -504,8 +504,8 @@ impl KeyBuilder { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let mut key = KeyBuilder::new() /// .with_indexes(vec!["test", "movies"]) /// .execute(&client) @@ -551,8 +551,8 @@ impl KeyBuilder { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let description = "My not so little lovely test key".to_string(); /// let mut key = KeyBuilder::new() /// .with_description(&description) @@ -577,8 +577,8 @@ impl KeyBuilder { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let name = "lovely key".to_string(); /// let mut key = KeyBuilder::new() /// .with_name(&name) @@ -603,8 +603,8 @@ impl KeyBuilder { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let uid = "93bcd7fb-2196-4fd9-acb7-3fca8a96e78f".to_string(); /// let mut key = KeyBuilder::new() /// .with_uid(&uid) @@ -629,8 +629,8 @@ impl KeyBuilder { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let description = "My little lovely test key".to_string(); /// let key = KeyBuilder::new() /// .with_description(&description) diff --git a/src/lib.rs b/src/lib.rs index e7ae60b9..553c4760 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,11 +15,12 @@ //! } //! //! -//! fn main() { block_on(async move { +//! #[tokio::main(flavor = "current_thread")] +//! async fn main() { //! # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); //! # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); //! // Create a client (without sending any request so that can't fail) -//! let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +//! let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); //! //! # let index = client.create_index("movies", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); //! // An index is where the documents are stored. @@ -35,7 +36,7 @@ //! Movie { id: 6, title: String::from("Philadelphia"), genres: vec!["Drama".to_string()] }, //! ], Some("id")).await.unwrap(); //! # index.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); -//! })} +//! } //! ``` //! //! With the `uid`, you can check the status (`enqueued`, `canceled`, `processing`, `succeeded` or `failed`) of your documents addition using the [task](https://www.meilisearch.com/docs/reference/api/tasks#get-task). @@ -45,17 +46,16 @@ //! ``` //! # use meilisearch_sdk::client::*; //! # use serde::{Serialize, Deserialize}; -//! # use futures::executor::block_on; //! # #[derive(Serialize, Deserialize, Debug)] //! # struct Movie { //! # id: usize, //! # title: String, //! # genres: Vec, //! # } -//! # fn main() { block_on(async move { +//! # fn main() { tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { //! # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); //! # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); -//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); //! # let movies = client.create_index("movies_2", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); //! // Meilisearch is typo-tolerant: //! println!("{:?}", client.index("movies_2").search().with_query("caorl").execute::().await.unwrap().hits); @@ -88,17 +88,16 @@ //! ``` //! # use meilisearch_sdk::{client::*, search::*}; //! # use serde::{Serialize, Deserialize}; -//! # use futures::executor::block_on; //! # #[derive(Serialize, Deserialize, Debug)] //! # struct Movie { //! # id: usize, //! # title: String, //! # genres: Vec, //! # } -//! # fn main() { block_on(async move { +//! # fn main() { tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { //! # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); //! # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); -//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); //! # let movies = client.create_index("movies_3", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); //! let search_result = client.index("movies_3") //! .search() @@ -141,11 +140,10 @@ //! ``` //! # use meilisearch_sdk::{client::*}; //! # use serde::{Serialize, Deserialize}; -//! # use futures::executor::block_on; -//! # fn main() { block_on(async move { +//! # fn main() { tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { //! # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); //! # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); -//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); //! # let movies = client.create_index("movies_4", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); //! let filterable_attributes = [ //! "id", @@ -165,17 +163,16 @@ //! ``` //! # use meilisearch_sdk::{client::*, search::*}; //! # use serde::{Serialize, Deserialize}; -//! # use futures::executor::block_on; //! # #[derive(Serialize, Deserialize, Debug)] //! # struct Movie { //! # id: usize, //! # title: String, //! # genres: Vec, //! # } -//! # fn main() { block_on(async move { +//! # fn main() { tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { //! # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); //! # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); -//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +//! # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); //! # let movies = client.create_index("movies_5", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); //! # let filterable_attributes = [ //! # "id", @@ -220,12 +217,11 @@ //! } //! ``` //! -//! ### Using users customized HttpClient +//! ### Customize the `HttpClient` //! -//! If you want to change the `HttpClient` you can incorporate using the `Client::new_with_client` method. -//! To use it, you need to implement the `HttpClient Trait`(`isahc` is used by default). -//! There are [using-reqwest-example](./examples/cli-app-with-reqwest) of using `reqwest`. - +//! By default, the SDK uses [`reqwest`](https://docs.rs/reqwest/latest/reqwest/) to make http calls. +//! The SDK lets you customize the http client by implementing the `HttpClient` trait yourself and +//! initializing the `Client` with the `new_with_client` method. #![warn(clippy::all)] #![allow(clippy::needless_doctest_main)] @@ -253,17 +249,18 @@ pub mod task_info; /// Module representing the [`Task`]s. pub mod tasks; /// Module that generates tenant tokens. +#[cfg(not(target_arch = "wasm32"))] mod tenant_tokens; /// Module containing utilizes functions. mod utils; -#[cfg(feature = "isahc")] -#[cfg(not(target_arch = "wasm32"))] -pub type DefaultHttpClient = request::IsahcClient; -#[cfg(target_arch = "wasm32")] -pub type DefaultHttpClient = request::WebSysClient; +#[cfg(feature = "reqwest")] +pub mod reqwest; + +#[cfg(feature = "reqwest")] +pub type DefaultHttpClient = reqwest::ReqwestClient; -#[cfg(not(feature = "isahc"))] +#[cfg(not(feature = "reqwest"))] pub type DefaultHttpClient = std::convert::Infallible; #[cfg(test)] diff --git a/src/request.rs b/src/request.rs index 1bfc1bf4..a81e1604 100644 --- a/src/request.rs +++ b/src/request.rs @@ -3,7 +3,7 @@ use std::convert::Infallible; use async_trait::async_trait; use log::{error, trace, warn}; use serde::{de::DeserializeOwned, Serialize}; -use serde_json::from_str; +use serde_json::{from_str, to_vec}; use crate::errors::{Error, MeilisearchCommunicationError, MeilisearchError}; @@ -16,66 +16,60 @@ pub enum Method { Delete { query: Q }, } -#[async_trait(?Send)] -pub trait HttpClient: Clone + Send + Sync { - async fn request( - self, - url: &str, - apikey: Option<&str>, - method: Method, - expected_status_code: u16, - ) -> Result - where - Query: Serialize + Send + Sync, - Body: Serialize + Send + Sync, - Output: DeserializeOwned + 'static + Send; - - #[cfg(not(target_arch = "wasm32"))] - async fn stream_request< - 'a, - Query: Serialize + Send + Sync, - Body: futures_io::AsyncRead + Send + Sync + 'static, - Output: DeserializeOwned + 'static, - >( - self, - url: &str, - apikey: Option<&str>, - method: Method, - content_type: &str, - expected_status_code: u16, - ) -> Result; -} - -#[cfg(feature = "isahc")] -#[derive(Debug, Clone, Copy, Default, Serialize)] -pub struct IsahcClient; +impl Method { + pub fn map_body(self, f: impl Fn(B) -> B2) -> Method { + match self { + Method::Get { query } => Method::Get { query }, + Method::Delete { query } => Method::Delete { query }, + Method::Post { query, body } => Method::Post { + query, + body: f(body), + }, + Method::Patch { query, body } => Method::Patch { + query, + body: f(body), + }, + Method::Put { query, body } => Method::Put { + query, + body: f(body), + }, + } + } -#[cfg(feature = "isahc")] -impl IsahcClient { - pub fn new() -> Self { - IsahcClient + pub fn query(&self) -> &Q { + match self { + Method::Get { query } => query, + Method::Delete { query } => query, + Method::Post { query, .. } => query, + Method::Put { query, .. } => query, + Method::Patch { query, .. } => query, + } } -} -#[cfg(target_arch = "wasm32")] -#[derive(Debug, Clone, Copy, Default, Serialize)] -pub struct WebSysClient; + pub fn body(&self) -> Option<&B> { + match self { + Method::Get { query: _ } | Method::Delete { query: _ } => None, + Method::Post { body, query: _ } => Some(body), + Method::Put { body, query: _ } => Some(body), + Method::Patch { body, query: _ } => Some(body), + } + } -#[cfg(target_arch = "wasm32")] -impl WebSysClient { - pub fn new() -> Self { - WebSysClient + pub fn into_body(self) -> Option { + match self { + Method::Get { query: _ } | Method::Delete { query: _ } => None, + Method::Post { body, query: _ } => Some(body), + Method::Put { body, query: _ } => Some(body), + Method::Patch { body, query: _ } => Some(body), + } } } -#[cfg(feature = "isahc")] -#[cfg(not(target_arch = "wasm32"))] #[async_trait(?Send)] -impl HttpClient for IsahcClient { +pub trait HttpClient: Clone + Send + Sync { async fn request( - self, + &self, url: &str, - apikey: Option<&str>, method: Method, expected_status_code: u16, ) -> Result @@ -84,323 +78,28 @@ impl HttpClient for IsahcClient { Body: Serialize + Send + Sync, Output: DeserializeOwned + 'static + Send, { - use isahc::http::header; - use isahc::http::method::Method as HttpMethod; - use isahc::*; - use serde_json::to_string; - - let builder = Request::builder().header(header::USER_AGENT, qualified_version()); - let builder = match apikey { - Some(apikey) => builder.header(header::AUTHORIZATION, format!("Bearer {apikey}")), - None => builder, - }; - - let mut response = match &method { - Method::Get { query } => { - let url = add_query_parameters(url, query)?; - - builder - .method(HttpMethod::GET) - .uri(url) - .body(()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Delete { query } => { - let url = add_query_parameters(url, query)?; - - builder - .method(HttpMethod::DELETE) - .uri(url) - .body(()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Post { query, body } => { - let url = add_query_parameters(url, query)?; - - builder - .method(HttpMethod::POST) - .uri(url) - .header(header::CONTENT_TYPE, "application/json") - .body(to_string(&body).unwrap()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Patch { query, body } => { - let url = add_query_parameters(url, query)?; - - builder - .method(HttpMethod::PATCH) - .uri(url) - .header(header::CONTENT_TYPE, "application/json") - .body(to_string(&body).unwrap()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Put { query, body } => { - let url = add_query_parameters(url, query)?; - - builder - .method(HttpMethod::PUT) - .uri(url) - .header(header::CONTENT_TYPE, "application/json") - .body(to_string(&body).unwrap()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - }; + use futures::io::Cursor; - let status = response.status().as_u16(); - - let mut body = response - .text() - .await - .map_err(|e| crate::errors::Error::HttpError(e.into()))?; - - if body.is_empty() { - body = "null".to_string(); - } - - parse_response(status, expected_status_code, &body, url.to_string()) - // parse_response(status, expected_status_code, body) + self.stream_request( + url, + method.map_body(|body| Cursor::new(to_vec(&body).unwrap())), + "application/json", + expected_status_code, + ) + .await } async fn stream_request< - 'a, Query: Serialize + Send + Sync, Body: futures_io::AsyncRead + Send + Sync + 'static, Output: DeserializeOwned + 'static, >( - self, + &self, url: &str, - apikey: Option<&str>, method: Method, content_type: &str, expected_status_code: u16, - ) -> Result { - use isahc::http::header; - use isahc::http::method::Method as HttpMethod; - use isahc::*; - - let builder = Request::builder().header(header::USER_AGENT, qualified_version()); - let builder = match apikey { - Some(apikey) => builder.header(header::AUTHORIZATION, format!("Bearer {apikey}")), - None => builder, - }; - - let mut response = match method { - Method::Get { query } => { - let url = add_query_parameters(url, &query)?; - - builder - .method(HttpMethod::GET) - .uri(url) - .body(()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Delete { query } => { - let url = add_query_parameters(url, &query)?; - - builder - .method(HttpMethod::DELETE) - .uri(url) - .body(()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Post { query, body } => { - let url = add_query_parameters(url, &query)?; - - builder - .method(HttpMethod::POST) - .uri(url) - .header(header::CONTENT_TYPE, content_type) - .body(AsyncBody::from_reader(body)) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Patch { query, body } => { - let url = add_query_parameters(url, &query)?; - - builder - .method(HttpMethod::PATCH) - .uri(url) - .header(header::CONTENT_TYPE, content_type) - .body(AsyncBody::from_reader(body)) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - Method::Put { query, body } => { - let url = add_query_parameters(url, &query)?; - - builder - .method(HttpMethod::PUT) - .uri(url) - .header(header::CONTENT_TYPE, content_type) - .body(AsyncBody::from_reader(body)) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? - } - }; - - let status = response.status().as_u16(); - - let mut body = response - .text() - .await - .map_err(|e| crate::errors::Error::HttpError(e.into()))?; - - if body.is_empty() { - body = "null".to_string(); - } - - parse_response(status, expected_status_code, &body, url.to_string()) - // parse_response(status, expected_status_code, body) - } -} - -#[cfg(target_arch = "wasm32")] -#[async_trait(?Send)] -impl HttpClient for WebSysClient { - async fn request( - self, - url: &str, - apikey: Option<&str>, - method: Method, - expected_status_code: u16, - ) -> Result - where - Query: Serialize + Send + Sync, - Body: Serialize + Send + Sync, - Output: DeserializeOwned + 'static, - { - use serde_json::to_string; - use wasm_bindgen::JsValue; - use wasm_bindgen_futures::JsFuture; - use web_sys::{Headers, RequestInit, Response}; - - const CONTENT_TYPE: &str = "Content-Type"; - const JSON: &str = "application/json"; - - // The 2 following unwraps should not be able to fail - let mut mut_url = url.clone().to_string(); - let headers = Headers::new().unwrap(); - if let Some(apikey) = apikey { - headers - .append("Authorization", format!("Bearer {}", apikey).as_str()) - .unwrap(); - } - headers - .append("X-Meilisearch-Client", qualified_version().as_str()) - .unwrap(); - - let mut request: RequestInit = RequestInit::new(); - request.headers(&headers); - - match &method { - Method::Get { query } => { - mut_url = add_query_parameters(mut_url, &query)?; - - request.method("GET"); - } - Method::Delete { query } => { - mut_url = add_query_parameters(mut_url, &query)?; - request.method("DELETE"); - } - Method::Patch { query, body } => { - mut_url = add_query_parameters(mut_url, &query)?; - request.method("PATCH"); - headers.append(CONTENT_TYPE, JSON).unwrap(); - request.body(Some(&JsValue::from_str(&to_string(body).unwrap()))); - } - Method::Post { query, body } => { - mut_url = add_query_parameters(mut_url, &query)?; - request.method("POST"); - headers.append(CONTENT_TYPE, JSON).unwrap(); - request.body(Some(&JsValue::from_str(&to_string(body).unwrap()))); - } - Method::Put { query, body } => { - mut_url = add_query_parameters(mut_url, &query)?; - request.method("PUT"); - headers.append(CONTENT_TYPE, JSON).unwrap(); - request.body(Some(&JsValue::from_str(&to_string(body).unwrap()))); - } - } - - let window = web_sys::window().unwrap(); // TODO remove this unwrap - let response = match JsFuture::from( - window.fetch_with_str_and_init(mut_url.as_str(), &request), - ) - .await - { - Ok(response) => Response::from(response), - Err(e) => { - error!("Network error: {:?}", e); - return Err(Error::UnreachableServer); - } - }; - let status = response.status() as u16; - let text = match response.text() { - Ok(text) => match JsFuture::from(text).await { - Ok(text) => text, - Err(e) => { - error!("Invalid response: {:?}", e); - return Err(Error::HttpError("Invalid response".to_string())); - } - }, - Err(e) => { - error!("Invalid response: {:?}", e); - return Err(Error::HttpError("Invalid response".to_string())); - } - }; - - if let Some(t) = text.as_string() { - if t.is_empty() { - parse_response(status, expected_status_code, "null", url.to_string()) - } else { - parse_response(status, expected_status_code, &t, url.to_string()) - } - } else { - error!("Invalid response"); - Err(Error::HttpError("Invalid utf8".to_string())) - } - } -} - -#[cfg(not(target_arch = "wasm32"))] -pub fn add_query_parameters(url: &str, query: &Query) -> Result { - let query = yaup::to_string(query)?; - - if query.is_empty() { - Ok(url.to_string()) - } else { - Ok(format!("{url}?{query}")) - } -} - -#[cfg(target_arch = "wasm32")] -pub fn add_query_parameters( - mut url: String, - query: &Query, -) -> Result { - let query = yaup::to_string(query)?; - - if !query.is_empty() { - url = format!("{}?{}", url, query); - }; - return Ok(url); + ) -> Result; } pub fn parse_response( @@ -444,18 +143,11 @@ pub fn parse_response( } } -pub fn qualified_version() -> String { - const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION"); - - format!("Meilisearch Rust (v{})", VERSION.unwrap_or("unknown")) -} - #[async_trait(?Send)] impl HttpClient for Infallible { async fn request( - self, + &self, _url: &str, - _apikey: Option<&str>, _method: Method, _expected_status_code: u16, ) -> Result @@ -467,16 +159,13 @@ impl HttpClient for Infallible { unreachable!() } - #[cfg(not(target_arch = "wasm32"))] async fn stream_request< - 'a, Query: Serialize + Send + Sync, Body: futures_io::AsyncRead + Send + Sync + 'static, Output: DeserializeOwned + 'static, >( - self, + &self, _url: &str, - _apikey: Option<&str>, _method: Method, _content_type: &str, _expected_status_code: u16, diff --git a/src/reqwest.rs b/src/reqwest.rs new file mode 100644 index 00000000..4c239ddb --- /dev/null +++ b/src/reqwest.rs @@ -0,0 +1,172 @@ +use std::{ + pin::Pin, + task::{Context, Poll}, +}; + +use async_trait::async_trait; +use bytes::{Bytes, BytesMut}; +use futures::{AsyncRead, Stream}; +use pin_project_lite::pin_project; +use serde::{de::DeserializeOwned, Serialize}; + +use crate::{ + errors::Error, + request::{parse_response, HttpClient, Method}, +}; + +#[derive(Debug, Clone, Default)] +pub struct ReqwestClient { + client: reqwest::Client, +} + +impl ReqwestClient { + pub fn new(api_key: Option<&str>) -> Result { + use reqwest::{header, ClientBuilder}; + + let builder = ClientBuilder::new(); + let mut headers = header::HeaderMap::new(); + #[cfg(not(target_arch = "wasm32"))] + headers.insert( + header::USER_AGENT, + header::HeaderValue::from_str(&qualified_version()).unwrap(), + ); + #[cfg(target_arch = "wasm32")] + headers.insert( + header::HeaderName::from_static("X-Meilisearch-Client"), + header::HeaderValue::from_str(&qualified_version()).unwrap(), + ); + + if let Some(api_key) = api_key { + headers.insert( + header::AUTHORIZATION, + header::HeaderValue::from_str(&format!("Bearer {api_key}")).unwrap(), + ); + } + + let builder = builder.default_headers(headers); + let client = builder.build()?; + + Ok(ReqwestClient { client }) + } +} + +#[async_trait(?Send)] +impl HttpClient for ReqwestClient { + async fn stream_request< + Query: Serialize + Send + Sync, + Body: futures_io::AsyncRead + Send + Sync + 'static, + Output: DeserializeOwned + 'static, + >( + &self, + url: &str, + method: Method, + content_type: &str, + expected_status_code: u16, + ) -> Result { + use reqwest::header; + + let query = method.query(); + let query = yaup::to_string(query)?; + + let url = if query.is_empty() { + url.to_string() + } else { + format!("{url}?{query}") + }; + + let mut request = self.client.request(verb(&method), &url); + + if let Some(body) = method.into_body() { + // TODO: Currently reqwest doesn't support streaming data in wasm so we need to collect everything in RAM + #[cfg(not(target_arch = "wasm32"))] + { + let stream = ReaderStream::new(body); + let body = reqwest::Body::wrap_stream(stream); + + request = request + .header(header::CONTENT_TYPE, content_type) + .body(body); + } + #[cfg(target_arch = "wasm32")] + { + use futures::{pin_mut, AsyncReadExt}; + + let mut buf = Vec::new(); + pin_mut!(body); + body.read_to_end(&mut buf) + .await + .map_err(|err| Error::Other(Box::new(err)))?; + request = request.header(header::CONTENT_TYPE, content_type).body(buf); + } + } + + let response = self.client.execute(request.build()?).await?; + let status = response.status().as_u16(); + let mut body = response.text().await?; + + if body.is_empty() { + body = "null".to_string(); + } + + parse_response(status, expected_status_code, &body, url.to_string()) + } +} + +fn verb(method: &Method) -> reqwest::Method { + match method { + Method::Get { .. } => reqwest::Method::GET, + Method::Delete { .. } => reqwest::Method::DELETE, + Method::Post { .. } => reqwest::Method::POST, + Method::Put { .. } => reqwest::Method::PUT, + Method::Patch { .. } => reqwest::Method::PATCH, + } +} + +pub fn qualified_version() -> String { + const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION"); + + format!("Meilisearch Rust (v{})", VERSION.unwrap_or("unknown")) +} + +pin_project! { + #[derive(Debug)] + pub struct ReaderStream { + #[pin] + reader: R, + buf: BytesMut, + capacity: usize, + } +} + +impl ReaderStream { + pub fn new(reader: R) -> Self { + Self { + reader, + buf: BytesMut::new(), + // 8KiB of capacity, the default capacity used by `BufReader` in the std + capacity: 8 * 1024 * 1024, + } + } +} + +impl Stream for ReaderStream { + type Item = std::io::Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.as_mut().project(); + + if this.buf.capacity() == 0 { + this.buf.resize(*this.capacity, 0); + } + + match AsyncRead::poll_read(this.reader, cx, this.buf) { + Poll::Pending => Poll::Pending, + Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), + Poll::Ready(Ok(0)) => Poll::Ready(None), + Poll::Ready(Ok(i)) => { + let chunk = this.buf.split_to(i); + Poll::Ready(Some(Ok(chunk.freeze()))) + } + } + } +} diff --git a/src/search.rs b/src/search.rs index f8982f28..ec96d9d7 100644 --- a/src/search.rs +++ b/src/search.rs @@ -160,8 +160,8 @@ type AttributeToCrop<'a> = (&'a str, Option); /// name: String, /// description: String, /// } -/// # futures::executor::block_on(async move { -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client /// # .create_index("search_query_builder", None) /// # .await @@ -190,7 +190,7 @@ type AttributeToCrop<'a> = (&'a str, Option); /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # -/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); +/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # let index = client.index("search_query_builder_build"); /// let query = index.search() /// .with_query("space") @@ -382,8 +382,8 @@ impl<'a, Http: HttpClient> SearchQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # #[derive(Serialize, Deserialize, Debug)] /// # struct Movie { /// # name: String, @@ -414,8 +414,8 @@ impl<'a, Http: HttpClient> SearchQuery<'a, Http> { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # #[derive(Serialize, Deserialize, Debug)] /// # struct Movie { /// # name: String, @@ -1146,7 +1146,7 @@ mod tests { .execute(&client) .await .unwrap(); - let allowed_client = Client::new(meilisearch_url, Some(key.key)); + let allowed_client = Client::new(meilisearch_url, Some(key.key)).unwrap(); let search_rules = vec![ json!({ "*": {}}), @@ -1161,7 +1161,7 @@ mod tests { .generate_tenant_token(key.uid.clone(), rules, None, None) .expect("Cannot generate tenant token."); - let new_client = Client::new(meilisearch_url, Some(token.clone())); + let new_client = Client::new(meilisearch_url, Some(token.clone())).unwrap(); let result: SearchResults = new_client .index(index.uid.to_string()) diff --git a/src/settings.rs b/src/settings.rs index 25a2fa16..de5aae70 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -299,8 +299,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_settings", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_settings"); /// @@ -311,10 +311,8 @@ impl Index { pub async fn get_settings(&self) -> Result { self.client .http_client - .clone() .request::<(), (), Settings>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -332,8 +330,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_synonyms", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_synonyms"); /// @@ -344,13 +342,11 @@ impl Index { pub async fn get_synonyms(&self) -> Result>, Error> { self.client .http_client - .clone() .request::<(), (), HashMap>>( &format!( "{}/indexes/{}/settings/synonyms", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -368,8 +364,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_pagination", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_pagination"); /// @@ -380,13 +376,11 @@ impl Index { pub async fn get_pagination(&self) -> Result { self.client .http_client - .clone() .request::<(), (), PaginationSetting>( &format!( "{}/indexes/{}/settings/pagination", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -403,8 +397,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_stop_words", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_stop_words"); /// @@ -415,13 +409,11 @@ impl Index { pub async fn get_stop_words(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Vec>( &format!( "{}/indexes/{}/settings/stop-words", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -439,8 +431,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_ranking_rules", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_ranking_rules"); /// @@ -451,13 +443,11 @@ impl Index { pub async fn get_ranking_rules(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Vec>( &format!( "{}/indexes/{}/settings/ranking-rules", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -475,8 +465,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_filterable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_filterable_attributes"); /// @@ -487,13 +477,11 @@ impl Index { pub async fn get_filterable_attributes(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Vec>( &format!( "{}/indexes/{}/settings/filterable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -511,8 +499,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_sortable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_sortable_attributes"); /// @@ -523,13 +511,11 @@ impl Index { pub async fn get_sortable_attributes(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Vec>( &format!( "{}/indexes/{}/settings/sortable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -547,8 +533,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_distinct_attribute", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_distinct_attribute"); /// @@ -559,13 +545,11 @@ impl Index { pub async fn get_distinct_attribute(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Option>( &format!( "{}/indexes/{}/settings/distinct-attribute", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -583,8 +567,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_searchable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_searchable_attributes"); /// @@ -595,13 +579,11 @@ impl Index { pub async fn get_searchable_attributes(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Vec>( &format!( "{}/indexes/{}/settings/searchable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -619,8 +601,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_displayed_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_displayed_attributes"); /// @@ -631,13 +613,11 @@ impl Index { pub async fn get_displayed_attributes(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Vec>( &format!( "{}/indexes/{}/settings/displayed-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -655,8 +635,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_faceting", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_faceting"); /// @@ -667,13 +647,11 @@ impl Index { pub async fn get_faceting(&self) -> Result { self.client .http_client - .clone() .request::<(), (), FacetingSettings>( &format!( "{}/indexes/{}/settings/faceting", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -690,8 +668,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_dictionary", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_dictionary"); /// @@ -702,13 +680,11 @@ impl Index { pub async fn get_dictionary(&self) -> Result, Error> { self.client .http_client - .clone() .request::<(), (), Vec>( &format!( "{}/indexes/{}/settings/dictionary", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -725,8 +701,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_proximity_precision", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_proximity_precision"); /// @@ -737,13 +713,11 @@ impl Index { pub async fn get_proximity_precision(&self) -> Result { self.client .http_client - .clone() .request::<(), (), String>( &format!( "{}/indexes/{}/settings/proximity-precision", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -758,8 +732,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("get_typo_tolerance", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_typo_tolerance"); /// @@ -770,13 +744,11 @@ impl Index { pub async fn get_typo_tolerance(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TypoToleranceSettings>( &format!( "{}/indexes/{}/settings/typo-tolerance", self.client.host, self.uid ), - self.client.get_api_key(), Method::Get { query: () }, 200, ) @@ -795,8 +767,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_settings", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_settings"); /// @@ -813,10 +785,8 @@ impl Index { pub async fn set_settings(&self, settings: &Settings) -> Result { self.client .http_client - .clone() .request::<(), &Settings, TaskInfo>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), - self.client.get_api_key(), Method::Patch { query: (), body: settings, @@ -836,8 +806,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_synonyms", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_synonyms"); /// @@ -856,13 +826,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), &HashMap>, TaskInfo>( &format!( "{}/indexes/{}/settings/synonyms", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: synonyms, @@ -882,8 +850,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_pagination", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_pagination"); /// @@ -895,13 +863,11 @@ impl Index { pub async fn set_pagination(&self, pagination: PaginationSetting) -> Result { self.client .http_client - .clone() .request::<(), &PaginationSetting, TaskInfo>( &format!( "{}/indexes/{}/settings/pagination", self.client.host, self.uid ), - self.client.get_api_key(), Method::Patch { query: (), body: &pagination, @@ -921,8 +887,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_stop_words", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_stop_words"); /// @@ -937,13 +903,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), Vec, TaskInfo>( &format!( "{}/indexes/{}/settings/stop-words", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: stop_words @@ -966,8 +930,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_ranking_rules", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_ranking_rules"); /// @@ -991,13 +955,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), Vec, TaskInfo>( &format!( "{}/indexes/{}/settings/ranking-rules", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: ranking_rules @@ -1020,8 +982,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_filterable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_filterable_attributes"); /// @@ -1036,13 +998,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), Vec, TaskInfo>( &format!( "{}/indexes/{}/settings/filterable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: filterable_attributes @@ -1065,8 +1025,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_sortable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_sortable_attributes"); /// @@ -1081,13 +1041,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), Vec, TaskInfo>( &format!( "{}/indexes/{}/settings/sortable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: sortable_attributes @@ -1110,8 +1068,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_distinct_attribute", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_distinct_attribute"); /// @@ -1125,13 +1083,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), String, TaskInfo>( &format!( "{}/indexes/{}/settings/distinct-attribute", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: distinct_attribute.as_ref().to_string(), @@ -1151,8 +1107,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_searchable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_searchable_attributes"); /// @@ -1166,13 +1122,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), Vec, TaskInfo>( &format!( "{}/indexes/{}/settings/searchable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: searchable_attributes @@ -1195,8 +1149,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_displayed_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_displayed_attributes"); /// @@ -1210,13 +1164,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), Vec, TaskInfo>( &format!( "{}/indexes/{}/settings/displayed-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: displayed_attributes @@ -1239,8 +1191,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_faceting", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_faceting"); /// @@ -1255,13 +1207,11 @@ impl Index { pub async fn set_faceting(&self, faceting: &FacetingSettings) -> Result { self.client .http_client - .clone() .request::<(), &FacetingSettings, TaskInfo>( &format!( "{}/indexes/{}/settings/faceting", self.client.host, self.uid ), - self.client.get_api_key(), Method::Patch { query: (), body: faceting, @@ -1281,8 +1231,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_dictionary", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_dictionary"); /// @@ -1296,13 +1246,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), Vec, TaskInfo>( &format!( "{}/indexes/{}/settings/dictionary", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: dictionary @@ -1325,8 +1273,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_typo_tolerance", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_typo_tolerance"); /// @@ -1347,13 +1295,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), &TypoToleranceSettings, TaskInfo>( &format!( "{}/indexes/{}/settings/typo-tolerance", self.client.host, self.uid ), - self.client.get_api_key(), Method::Patch { query: (), body: typo_tolerance, @@ -1373,8 +1319,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("set_proximity_precision", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_proximity_precision"); /// @@ -1388,13 +1334,11 @@ impl Index { ) -> Result { self.client .http_client - .clone() .request::<(), String, TaskInfo>( &format!( "{}/indexes/{}/settings/proximity-precision", self.client.host, self.uid ), - self.client.get_api_key(), Method::Put { query: (), body: proximity_precision, @@ -1416,8 +1360,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_settings", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_settings"); /// @@ -1428,10 +1372,8 @@ impl Index { pub async fn reset_settings(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1448,8 +1390,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_synonyms", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_synonyms"); /// @@ -1460,13 +1402,11 @@ impl Index { pub async fn reset_synonyms(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/synonyms", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1483,8 +1423,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_pagination", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_pagination"); /// @@ -1495,13 +1435,11 @@ impl Index { pub async fn reset_pagination(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/pagination", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1517,8 +1455,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_stop_words", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_stop_words"); /// @@ -1529,13 +1467,11 @@ impl Index { pub async fn reset_stop_words(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/stop-words", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1554,8 +1490,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_ranking_rules", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_ranking_rules"); /// @@ -1566,13 +1502,11 @@ impl Index { pub async fn reset_ranking_rules(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/ranking-rules", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1589,8 +1523,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_filterable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_filterable_attributes"); /// @@ -1601,13 +1535,11 @@ impl Index { pub async fn reset_filterable_attributes(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/filterable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1624,8 +1556,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_sortable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_sortable_attributes"); /// @@ -1636,13 +1568,11 @@ impl Index { pub async fn reset_sortable_attributes(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/sortable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1659,8 +1589,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_distinct_attribute", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_distinct_attribute"); /// @@ -1671,13 +1601,11 @@ impl Index { pub async fn reset_distinct_attribute(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/distinct-attribute", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1695,8 +1623,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_searchable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_searchable_attributes"); /// @@ -1707,13 +1635,11 @@ impl Index { pub async fn reset_searchable_attributes(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/searchable-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1730,8 +1656,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_displayed_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_displayed_attributes"); /// @@ -1742,13 +1668,11 @@ impl Index { pub async fn reset_displayed_attributes(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/displayed-attributes", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1765,8 +1689,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_faceting", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_faceting"); /// @@ -1777,13 +1701,11 @@ impl Index { pub async fn reset_faceting(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/faceting", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1800,8 +1722,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_dictionary", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_dictionary"); /// @@ -1812,13 +1734,11 @@ impl Index { pub async fn reset_dictionary(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/dictionary", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1835,8 +1755,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_typo_tolerance", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_typo_tolerance"); /// @@ -1847,13 +1767,11 @@ impl Index { pub async fn reset_typo_tolerance(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/typo-tolerance", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) @@ -1870,8 +1788,8 @@ impl Index { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// # client.create_index("reset_proximity_precision", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_proximity_precision"); /// @@ -1882,13 +1800,11 @@ impl Index { pub async fn reset_proximity_precision(&self) -> Result { self.client .http_client - .clone() .request::<(), (), TaskInfo>( &format!( "{}/indexes/{}/settings/proximity-precision", self.client.host, self.uid ), - self.client.get_api_key(), Method::Delete { query: () }, 202, ) diff --git a/src/task_info.rs b/src/task_info.rs index 1e872c0d..c65c2186 100644 --- a/src/task_info.rs +++ b/src/task_info.rs @@ -54,8 +54,8 @@ impl TaskInfo { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("movies_wait_for_completion"); /// /// let status = movies.add_documents(&[ diff --git a/src/tasks.rs b/src/tasks.rs index c9299e0b..37babd2f 100644 --- a/src/tasks.rs +++ b/src/tasks.rs @@ -263,8 +263,8 @@ impl Task { /// # } /// # /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let movies = client.index("movies_wait_for_completion"); /// /// let status = movies.add_documents(&[ @@ -302,9 +302,9 @@ impl Task { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// # // create the client - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let task = client.create_index("try_make_index", None).await.unwrap(); /// let index = client.wait_for_task(task, None, None).await.unwrap().try_make_index(&client).unwrap(); /// @@ -343,8 +343,8 @@ impl Task { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let task = client.create_index("unwrap_failure", None).await.unwrap(); /// let task = client /// .create_index("unwrap_failure", None) @@ -382,8 +382,8 @@ impl Task { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let task = client.create_index("is_failure", None).await.unwrap(); /// // create an index with a conflicting uid /// let task = client @@ -413,8 +413,8 @@ impl Task { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let task = client /// .create_index("is_success", None) /// .await @@ -443,8 +443,8 @@ impl Task { /// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700"); /// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey"); /// # - /// # futures::executor::block_on(async move { - /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)); + /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { + /// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); /// let task_info = client /// .create_index("is_pending", None) /// .await @@ -888,7 +888,7 @@ mod test { async fn test_get_tasks_no_params() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks"; let mock_res = s.mock("GET", path).with_status(200).create_async().await; @@ -902,7 +902,7 @@ mod test { async fn test_get_tasks_with_params() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks?indexUids=movies,test&statuses=equeued&types=documentDeletion&uids=1&limit=0&from=1"; @@ -928,7 +928,7 @@ mod test { async fn test_get_tasks_with_date_params() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks?\ beforeEnqueuedAt=2022-02-03T13%3A02%3A38.369634Z\ &afterEnqueuedAt=2023-02-03T13%3A02%3A38.369634Z\ @@ -993,7 +993,7 @@ mod test { async fn test_get_tasks_on_struct_with_params() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks?indexUids=movies,test&statuses=equeued&types=documentDeletion&canceledBy=9"; @@ -1051,7 +1051,7 @@ mod test { async fn test_cancel_tasks_with_params() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks/cancel?indexUids=movies,test&statuses=equeued&types=documentDeletion&uids=1"; @@ -1075,7 +1075,7 @@ mod test { async fn test_cancel_tasks_with_params_execute() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks/cancel?indexUids=movies,test&statuses=equeued&types=documentDeletion&uids=1"; @@ -1099,7 +1099,7 @@ mod test { async fn test_delete_tasks_with_params() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks?indexUids=movies,test&statuses=equeued&types=documentDeletion&uids=1"; let mock_res = s.mock("DELETE", path).with_status(200).create_async().await; @@ -1122,7 +1122,7 @@ mod test { async fn test_delete_tasks_with_params_execute() -> Result<(), Error> { let mut s = mockito::Server::new_async().await; let mock_server_url = s.url(); - let client = Client::new(mock_server_url, Some("masterKey")); + let client = Client::new(mock_server_url, Some("masterKey")).unwrap(); let path = "/tasks?indexUids=movies,test&statuses=equeued&types=documentDeletion&uids=1"; let mock_res = s.mock("DELETE", path).with_status(200).create_async().await; diff --git a/src/tenant_tokens.rs b/src/tenant_tokens.rs index 80d12a23..bb561f71 100644 --- a/src/tenant_tokens.rs +++ b/src/tenant_tokens.rs @@ -7,7 +7,6 @@ use time::OffsetDateTime; use uuid::Uuid; #[derive(Debug, Serialize, Deserialize)] -#[cfg(not(target_arch = "wasm32"))] #[serde(rename_all = "camelCase")] struct TenantTokenClaim { api_key_uid: String, @@ -16,7 +15,6 @@ struct TenantTokenClaim { exp: Option, } -#[cfg(not(target_arch = "wasm32"))] pub fn generate_tenant_token( api_key_uid: String, search_rules: Value, diff --git a/src/utils.rs b/src/utils.rs index 3d378c47..65f93ff7 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -15,7 +15,7 @@ pub(crate) async fn async_sleep(interval: Duration) { use std::convert::TryInto; use wasm_bindgen_futures::JsFuture; - JsFuture::from(js_sys::Promise::new(&mut |yes, _| { + JsFuture::from(web_sys::js_sys::Promise::new(&mut |yes, _| { web_sys::window() .unwrap() .set_timeout_with_callback_and_timeout_and_arguments_0( @@ -36,7 +36,7 @@ mod test { #[meilisearch_test] async fn test_async_sleep() { let sleep_duration = Duration::from_millis(10); - let now = time::Instant::now(); + let now = std::time::Instant::now(); async_sleep(sleep_duration).await;