diff --git a/.code-samples.meilisearch.yaml b/.code-samples.meilisearch.yaml index 2385f7d5..6b52c6f8 100644 --- a/.code-samples.meilisearch.yaml +++ b/.code-samples.meilisearch.yaml @@ -397,7 +397,7 @@ add_movies_json_1: |- use futures::executor::block_on; fn main() { block_on(async move { - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); // reading and parsing the file let mut file = File::open("movies.json").unwrap(); @@ -496,7 +496,7 @@ getting_started_add_documents_md: |- use futures::executor::block_on; fn main() { block_on(async move { - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); // reading and parsing the file let mut file = File::open("movies.json").unwrap(); @@ -578,7 +578,7 @@ getting_started_update_displayedAttributes: |- client.index("movies").set_displayed_attributes(&displayed_attributes).await.unwrap(); getting_started_communicating_with_a_protected_instance: |- - let client = Client::new("http://localhost:7700", "apiKey"); + let client = Client::new("http://localhost:7700", Some("apiKey")); client.index("movies").search() getting_started_add_meteorites: |- use serde::{Serialize, Deserialize}; @@ -774,32 +774,32 @@ delete_a_key_1: |- let key = client.get_key("d0552b41536279a0ad88bd595327b96f01176a60c2243e906c52ac02375f9bc4").await.unwrap(); client.delete_key(&key); authorization_header_1: - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); let keys = client.get_keys().await.unwrap(); security_guide_search_key_1: |- - let client = Client::new("http://localhost:7700", "apiKey"); + let client = Client::new("http://localhost:7700", Some("apiKey")); let result = client.index("patient_medical_records").search().execute().await.unwrap(); security_guide_update_key_1: |- - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); let key = client.get_key("d0552b41536279a0ad88bd595327b96f01176a60c2243e906c52ac02375f9bc4").await.unwrap(); key.indexes = vec!["doctors".to_string()]; let updated_key = client.update_key(&key); security_guide_create_key_1: |- - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); let mut key_options = KeyBuilder::new("Search patient records key"); key_options.with_action(Action::Search) .with_expires_at(time::macros::datetime!(2023 - 01 - 01 00:00:00 UTC)) .with_index("patient_medical_records"); let new_key = client.create_key(key_options).await.unwrap(); security_guide_list_keys_1: |- - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); let keys = client.get_keys().await.unwrap(); security_guide_delete_key_1: |- - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); let key = client.get_key("d0552b41536279a0ad88bd595327b96f01176a60c2243e906c52ac02375f9bc4").await.unwrap(); client.delete_key(&key); landing_getting_started_1: |- - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); #[derive(Serialize, Deserialize)] struct Movie { @@ -822,7 +822,7 @@ tenant_token_guide_generate_sdk_1: |- let token = client.generate_tenant_token(search_rules, api_key, expires_at).unwrap(); tenant_token_guide_search_sdk_1: |- - let front_end_client = Client::new("http://127.0.0.1:7700", token); + let front_end_client = Client::new("http://127.0.0.1:7700", Some(token)); let results: SearchResults = front_end_client.index("patient_medical_records") .search() .with_query("blood test") diff --git a/README.md b/README.md index 1007dd68..f5c275c9 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ struct Movie { fn main() { block_on(async move { // Create a client (without sending any request so that can't fail) - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", some("masterKey")); // An index is where the documents are stored. let movies = client.index("movies"); diff --git a/examples/cli-app/src/main.rs b/examples/cli-app/src/main.rs index 1aaa8bd5..f2c3551e 100644 --- a/examples/cli-app/src/main.rs +++ b/examples/cli-app/src/main.rs @@ -7,7 +7,7 @@ use std::io::stdin; // instantiate the client. load it once lazy_static! { - static ref CLIENT: Client = Client::new("http://localhost:7700", "masterKey"); + static ref CLIENT: Client = Client::new("http://localhost:7700", Some("masterKey")); } fn main() { diff --git a/examples/settings.rs b/examples/settings.rs index 106e9d79..64952697 100644 --- a/examples/settings.rs +++ b/examples/settings.rs @@ -5,7 +5,7 @@ use meilisearch_sdk::settings::Settings; // we need an async runtime #[tokio::main(flavor = "current_thread")] async fn main() { - let client: Client = Client::new("http://localhost:7700", "masterKey"); + let client: Client = Client::new("http://localhost:7700", Some("masterKey")); // 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 921a1f7a..91a00558 100644 --- a/examples/web_app/src/lib.rs +++ b/examples/web_app/src/lib.rs @@ -17,8 +17,8 @@ use crate::document::{display, Crate}; lazy_static! { static ref CLIENT: Client = Client::new( "https://finding-demos.meilisearch.com", - "2b902cce4f868214987a9f3c7af51a69fa660d74a785bed258178b96e3480bb3", - ); + Some("2b902cce4f868214987a9f3c7af51a69fa660d74a785bed258178b96e3480bb3")), + ; } struct Model { diff --git a/meilisearch-test-macro/README.md b/meilisearch-test-macro/README.md index 56c30e5c..54ebf443 100644 --- a/meilisearch-test-macro/README.md +++ b/meilisearch-test-macro/README.md @@ -13,7 +13,7 @@ Before explaining its usage, we're going to see a simple test *before* this macr ```rust #[async_test] async fn test_get_tasks() -> Result<(), Error> { - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); let index = client .create_index("test_get_tasks", None) @@ -36,7 +36,7 @@ async fn test_get_tasks() -> Result<(), Error> { ``` I have multiple problems with this test: -- `let client = Client::new("http://localhost:7700", "masterKey");`: This line is always the same in every test. +- `let client = Client::new("http://localhost:7700", Some("masterKey"));`: This line is always the same in every test. And if you make a typo on the http addr or the master key, you'll have an error. - `let index = client.create_index("test_get_tasks", None)...`: Each test needs to have an unique name. This means we currently need to write the name of the test everywhere; it's not practical. @@ -61,7 +61,7 @@ the test, the macro automatically did the same thing we've seen before. There are a few rules, though: 1. The macro only handles three types of arguments: - `String`: It returns the name of the test. - - `Client`: It creates a client like that: `Client::new("http://localhost:7700", "masterKey")`. + - `Client`: It creates a client like that: `Client::new("http://localhost:7700", some("masterKey"))`. - `Index`: It creates and deletes an index, as we've seen before. 2. You only get what you asked for. That means if you don't ask for an index, no index will be created in meilisearch. So, if you are testing the creation of indexes, you can ask for a `Client` and a `String` and then create it yourself. diff --git a/meilisearch-test-macro/src/lib.rs b/meilisearch-test-macro/src/lib.rs index 8ca9546e..c201b89e 100644 --- a/meilisearch-test-macro/src/lib.rs +++ b/meilisearch-test-macro/src/lib.rs @@ -83,7 +83,7 @@ pub fn meilisearch_test(params: TokenStream, input: TokenStream) -> TokenStream // First we need to check if a client will be used and create it if it’s the case if use_client { outer_block.push(parse_quote!( - let client = Client::new("http://localhost:7700", "masterKey"); + let client = Client::new("http://localhost:7700", Some("masterKey")); )); } diff --git a/src/client.rs b/src/client.rs index bcbecdd0..33217cc0 100644 --- a/src/client.rs +++ b/src/client.rs @@ -14,7 +14,7 @@ use time::OffsetDateTime; #[derive(Debug, Clone)] pub struct Client { pub(crate) host: Arc, - pub(crate) api_key: Arc, + pub(crate) api_key: Arc>, } impl Client { @@ -27,12 +27,12 @@ impl Client { /// # use meilisearch_sdk::{client::*, indexes::*}; /// # /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// ``` - pub fn new(host: impl Into, api_key: impl Into) -> Client { + pub fn new(host: impl Into, api_key: Option>) -> Client { Client { host: Arc::new(host.into()), - api_key: Arc::new(api_key.into()), + api_key: Arc::new(api_key.map(|key| key.into())), } } @@ -44,7 +44,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// /// let indexes: Vec = client.list_all_indexes().await.unwrap(); /// println!("{:?}", indexes); @@ -66,7 +66,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// /// let json_indexes = client.list_all_indexes_raw().await.unwrap(); /// println!("{:?}", json_indexes); @@ -75,7 +75,7 @@ impl Client { pub async fn list_all_indexes_raw(&self) -> Result, Error> { let json_indexes = request::<(), Vec>( &format!("{}/indexes", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -93,7 +93,7 @@ impl Client { /// /// # futures::executor::block_on(async move { /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let index = client.create_index("get_index", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// /// // get the index named "get_index" @@ -117,7 +117,7 @@ impl Client { /// /// # futures::executor::block_on(async move { /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let index = client.create_index("get_raw_index", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// /// // get the index named "get_raw_index" @@ -130,7 +130,7 @@ impl Client { pub async fn get_raw_index(&self, uid: impl AsRef) -> Result { request::<(), Value>( &format!("{}/indexes/{}", self.host, uid.as_ref()), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -158,7 +158,7 @@ impl Client { /// # /// # futures::executor::block_on(async move { /// // Create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// /// // Create a new index called movies and access it /// let task = client.create_index("create_index", None).await.unwrap(); @@ -180,7 +180,7 @@ impl Client { ) -> Result { request::( &format!("{}/indexes", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Post(json!({ "uid": uid.as_ref(), "primaryKey": primary_key, @@ -195,7 +195,7 @@ impl Client { pub async fn delete_index(&self, uid: impl AsRef) -> Result { request::<(), Task>( &format!("{}/indexes/{}", self.host, uid.as_ref()), - &self.api_key, + self.api_key.as_deref(), Method::Delete, 202, ) @@ -220,14 +220,14 @@ impl Client { /// # use meilisearch_sdk::{client::*, indexes::*}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let stats = client.get_stats().await.unwrap(); /// # }); /// ``` pub async fn get_stats(&self) -> Result { request::( &format!("{}/stats", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -242,7 +242,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, errors::{Error, ErrorCode}}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let health = client.health().await.unwrap(); /// assert_eq!(health.status, "available"); /// # }); @@ -250,7 +250,7 @@ impl Client { pub async fn health(&self) -> Result { request::( &format!("{}/health", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -265,7 +265,7 @@ impl Client { /// # use meilisearch_sdk::client::*; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let health = client.is_healthy().await; /// assert_eq!(health, true); /// # }); @@ -289,7 +289,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, errors::Error, key::KeyBuilder}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let keys = client.get_keys().await.unwrap(); /// assert!(keys.len() >= 2); /// # }); @@ -304,7 +304,7 @@ impl Client { let keys = request::<(), Keys>( &format!("{}/keys", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -324,7 +324,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, errors::Error, key::KeyBuilder}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let key = client.get_keys().await.unwrap().into_iter().find(|k| k.description.starts_with("Default Search API Key")).unwrap(); /// let key_id = // enter your API key here, for the example we'll say we entered our search API key. /// # key.key; @@ -335,7 +335,7 @@ impl Client { pub async fn get_key(&self, key: impl AsRef) -> Result { request::<(), Key>( &format!("{}/keys/{}", self.host, key.as_ref()), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -353,7 +353,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, errors::Error, key::KeyBuilder}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let key = KeyBuilder::new("delete_key"); /// let key = client.create_key(key).await.unwrap(); /// let inner_key = key.key.clone(); @@ -367,7 +367,7 @@ impl Client { pub async fn delete_key(&self, key: impl AsRef) -> Result<(), Error> { request::<(), ()>( &format!("{}/keys/{}", self.host, key.as_ref()), - &self.api_key, + self.api_key.as_deref(), Method::Delete, 204, ) @@ -385,7 +385,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, errors::Error, key::KeyBuilder, key::Action}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let mut key = KeyBuilder::new("create_key"); /// key.with_index("*").with_action(Action::DocumentsAdd); /// let key = client.create_key(key).await.unwrap(); @@ -396,7 +396,7 @@ impl Client { pub async fn create_key(&self, key: impl AsRef) -> Result { request::<&KeyBuilder, Key>( &format!("{}/keys", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Post(key.as_ref()), 201, ) @@ -414,7 +414,7 @@ impl Client { /// # use meilisearch_sdk::{client::*, errors::Error, key::KeyBuilder}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let key = KeyBuilder::new("update_key"); /// let mut key = client.create_key(key).await.unwrap(); /// assert!(key.indexes.is_empty()); @@ -428,7 +428,7 @@ impl Client { pub async fn update_key(&self, key: impl AsRef) -> Result { request::<&Key, Key>( &format!("{}/keys/{}", self.host, key.as_ref().key), - &self.api_key, + self.api_key.as_deref(), Method::Patch(key.as_ref()), 200, ) @@ -443,14 +443,14 @@ impl Client { /// # use meilisearch_sdk::{client::*}; /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let version = client.get_version().await.unwrap(); /// # }); /// ``` pub async fn get_version(&self) -> Result { request::<(), Version>( &format!("{}/version", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -481,7 +481,7 @@ impl Client { /// # /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movies = client.index("movies_client_wait_for_task"); /// /// let task = movies.add_documents(&[ @@ -534,7 +534,7 @@ impl Client { /// ``` /// # use meilisearch_sdk::*; /// # futures::executor::block_on(async move { - /// # let client = client::Client::new("http://localhost:7700", "masterKey"); + /// # let client = client::Client::new("http://localhost:7700", Some("masterKey")); /// # 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(); /// let task = client.get_task(task).await.unwrap(); @@ -544,7 +544,7 @@ impl Client { pub async fn get_task(&self, task_id: impl AsRef) -> Result { request::<(), Task>( &format!("{}/tasks/{}", self.host, task_id.as_ref()), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -558,7 +558,7 @@ impl Client { /// ``` /// # use meilisearch_sdk::*; /// # futures::executor::block_on(async move { - /// # let client = client::Client::new("http://localhost:7700", "masterKey"); + /// # let client = client::Client::new("http://localhost:7700", Some("masterKey")); /// let tasks = client.get_tasks().await.unwrap(); /// # }); /// ``` @@ -570,7 +570,7 @@ impl Client { let tasks = request::<(), Tasks>( &format!("{}/tasks", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) @@ -586,18 +586,22 @@ impl Client { /// ``` /// # use meilisearch_sdk::*; /// # futures::executor::block_on(async move { - /// # let client = client::Client::new("http://localhost:7700", "masterKey"); + /// # let client = client::Client::new("http://localhost:7700", Some("masterKey")); /// let token = client.generate_tenant_token(serde_json::json!(["*"]), None, None).unwrap(); - /// let client = client::Client::new("http://localhost:7700", token); + /// let client = client::Client::new("http://localhost:7700", Some(token)); /// # }); /// ``` pub fn generate_tenant_token( &self, search_rules: serde_json::Value, - api_key: Option<&str>, + api_key: Option, expires_at: Option, ) -> Result { - let api_key = api_key.unwrap_or(&self.api_key); + let self_key = match self.api_key.as_ref() { + Some(key) => key, + None => "", + }; + let api_key = api_key.unwrap_or_else(|| String::from(self_key)); crate::tenant_tokens::generate_tenant_token(search_rules, api_key, expires_at) } @@ -654,9 +658,9 @@ mod tests { key::{Action, KeyBuilder}, }; use meilisearch_test_macro::meilisearch_test; - use time::OffsetDateTime; use mockito::mock; use std::mem; + use time::OffsetDateTime; #[meilisearch_test] async fn test_methods_has_qualified_version_as_header() { @@ -667,25 +671,35 @@ mod tests { let assertions = vec![ ( - mock("GET", path).match_header("User-Agent", user_agent).create(), - request::(address, "", Method::Get, 200) + mock("GET", path) + .match_header("User-Agent", user_agent) + .create(), + request::(address, None, Method::Get, 200), ), ( - mock("POST", path).match_header("User-Agent", user_agent).create(), - request::(address, "", Method::Post("".to_string()), 200) + mock("POST", path) + .match_header("User-Agent", user_agent) + .create(), + request::(address, None, Method::Post("".to_string()), 200), ), ( - mock("DELETE", path).match_header("User-Agent", user_agent).create(), - request::(address, "", Method::Delete, 200) + mock("DELETE", path) + .match_header("User-Agent", user_agent) + .create(), + request::(address, None, Method::Delete, 200), ), ( - mock("PUT", path).match_header("User-Agent", user_agent).create(), - request::(address, "", Method::Put("".to_string()), 200) + mock("PUT", path) + .match_header("User-Agent", user_agent) + .create(), + request::(address, None, Method::Put("".to_string()), 200), ), ( - mock("PATCH", path).match_header("User-Agent", user_agent).create(), - request::(address, "", Method::Patch("".to_string()), 200) - ) + mock("PATCH", path) + .match_header("User-Agent", user_agent) + .create(), + request::(address, None, Method::Patch("".to_string()), 200), + ), ]; for (m, req) in assertions { @@ -737,7 +751,7 @@ mod tests { let master_key = client.api_key.clone(); // this key has no right - client.api_key = Arc::new(key.key.clone()); + client.api_key = Arc::new(Option::from(key.key.clone())); // with a wrong key let error = client.delete_key("invalid_key").await.unwrap_err(); assert!(matches!( @@ -822,7 +836,8 @@ mod tests { // backup the master key for cleanup at the end of the test let master_client = client.clone(); - client.api_key = Arc::new(no_right_key.key.clone()); + + client.api_key = Arc::new(Some(no_right_key.key.clone())); let key = KeyBuilder::new(&description); let error = client.create_key(key).await.unwrap_err(); @@ -836,8 +851,12 @@ mod tests { }) )); + let key = match client.api_key.as_ref() { + Some(key) => key, + None => panic!("test_error_create_key no key to delete"), + }; // cleanup - master_client.delete_key(&*client.api_key).await.unwrap(); + master_client.delete_key(key).await.unwrap(); } #[meilisearch_test] @@ -903,7 +922,7 @@ mod tests { // backup the master key for cleanup at the end of the test let master_client = client.clone(); - client.api_key = Arc::new(no_right_key.key.clone()); + client.api_key = Arc::new(Option::from(no_right_key.key.clone())); let error = client.update_key(key).await.unwrap_err(); @@ -916,8 +935,11 @@ mod tests { }) )); - // cleanup - master_client.delete_key(&*client.api_key).await.unwrap(); + let key = match &*client.api_key { + Some(key) => key, + None => panic!("no key on test: test error update key"), + }; + master_client.delete_key(key).await.unwrap(); } #[meilisearch_test] diff --git a/src/dumps.rs b/src/dumps.rs index d04749e5..f2ff4841 100644 --- a/src/dumps.rs +++ b/src/dumps.rs @@ -20,7 +20,7 @@ //! # use std::{thread::sleep, time::Duration}; //! # futures::executor::block_on(async move { //! # -//! let client = Client::new("http://localhost:7700", "masterKey"); +//! let client = Client::new("http://localhost:7700", Some("masterKey")); //! //! // Create a dump //! let dump_info = client.create_dump().await.unwrap(); @@ -79,7 +79,7 @@ impl Client { /// # use std::{thread::sleep, time::Duration}; /// # futures::executor::block_on(async move { /// # - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// # let client = Client::new("http://localhost:7700", Some("masterKey")); /// # /// let dump_info = client.create_dump().await.unwrap(); /// assert!(matches!(dump_info.status, DumpStatus::InProgress)); @@ -88,7 +88,7 @@ impl Client { pub async fn create_dump(&self) -> Result { request::<(), DumpInfo>( &format!("{}/dumps", self.host), - &self.api_key, + self.api_key.as_deref(), Method::Post(()), 202, ) @@ -105,7 +105,7 @@ impl Client { /// # use std::{thread::sleep, time::Duration}; /// # futures::executor::block_on(async move { /// # - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// # let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let dump_info = client.create_dump().await.unwrap(); /// # sleep(Duration::from_secs(5)); /// # @@ -115,7 +115,7 @@ impl Client { pub async fn get_dump_status(&self, dump_uid: impl AsRef) -> Result { request::<(), DumpInfo>( &format!("{}/dumps/{}/status", self.host, dump_uid.as_ref()), - &self.api_key, + self.api_key.as_deref(), Method::Get, 200, ) diff --git a/src/errors.rs b/src/errors.rs index ba400d82..c477ca8b 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -24,7 +24,7 @@ pub enum Error { TenantTokensInvalidApiKey, /// It is not possible to generate an already expired tenant token. TenantTokensExpiredSignature, - + /// When jsonwebtoken cannot generate the token successfully. InvalidTenantToken(jsonwebtoken::errors::Error), diff --git a/src/indexes.rs b/src/indexes.rs index 4feef665..9ca89ccf 100644 --- a/src/indexes.rs +++ b/src/indexes.rs @@ -13,7 +13,7 @@ use time::OffsetDateTime; /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { -/// let client = Client::new("http://localhost:7700", "masterKey"); +/// let client = Client::new("http://localhost:7700", Some("masterKey")); /// /// // get the index called movies or create it if it does not exist /// let movies = client @@ -37,7 +37,7 @@ use time::OffsetDateTime; /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { -/// let client = Client::new("http://localhost:7700", "masterKey"); +/// let client = Client::new("http://localhost:7700", Some("masterKey")); /// /// // use the implicit index creation if the index already exist or /// // Meilisearch would be able to create the index if it does not exist during: @@ -88,7 +88,7 @@ impl Index { pub async fn update(&self, primary_key: impl AsRef) -> Result<(), Error> { request::( &format!("{}/indexes/{}", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Put(json!({ "primaryKey": primary_key.as_ref() })), 200, ) @@ -103,7 +103,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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 @@ -115,7 +115,7 @@ impl Index { pub async fn delete(self) -> Result { request::<(), Task>( &format!("{}/indexes/{}", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -138,7 +138,7 @@ impl Index { /// } /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movies = client.index("execute_query"); /// /// // add some documents @@ -156,7 +156,7 @@ impl Index { ) -> Result, Error> { request::<&Query, SearchResults>( &format!("{}/indexes/{}/search", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post(query), 200, ) @@ -179,7 +179,7 @@ impl Index { /// } /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let mut movies = client.index("search"); /// /// // add some documents @@ -219,7 +219,7 @@ impl Index { /// /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// 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(); /// @@ -239,7 +239,7 @@ impl Index { "{}/indexes/{}/documents/{}", self.client.host, self.uid, uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -269,7 +269,7 @@ impl Index { /// /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// 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(); @@ -302,7 +302,7 @@ impl Index { url.push_str("attributesToRetrieve="); url.push_str(attributes_to_retrieve); } - request::<(), Vec>(&url, &self.client.api_key, Method::Get, 200).await + request::<(), Vec>(&url, self.client.api_key.as_deref(), Method::Get, 200).await } /// Add a list of [Document]s or replace them if they already exist. @@ -329,7 +329,7 @@ impl Index { /// } /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movie_index = client.index("add_or_replace"); /// /// let task = movie_index.add_or_replace(&[ @@ -368,7 +368,13 @@ impl Index { } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; - request::<&[T], Task>(&url, &self.client.api_key, Method::Post(documents), 202).await + request::<&[T], Task>( + &url, + self.client.api_key.as_deref(), + Method::Post(documents), + 202, + ) + .await } /// Alias for [Index::add_or_replace]. @@ -402,7 +408,7 @@ impl Index { /// } /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movie_index = client.index("add_or_update"); /// /// let task = movie_index.add_or_update(&[ @@ -444,7 +450,13 @@ impl Index { } else { format!("{}/indexes/{}/documents", self.client.host, self.uid) }; - request::<&[T], Task>(&url, &self.client.api_key, Method::Put(documents), 202).await + request::<&[T], Task>( + &url, + self.client.api_key.as_deref(), + Method::Put(documents), + 202, + ) + .await } /// Delete all documents in the index. @@ -464,7 +476,7 @@ impl Index { /// # /// # futures::executor::block_on(async move { /// # - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// 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(); @@ -484,7 +496,7 @@ impl Index { pub async fn delete_all_documents(&self) -> Result { request::<(), Task>( &format!("{}/indexes/{}/documents", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -508,7 +520,7 @@ impl Index { /// # /// # futures::executor::block_on(async move { /// # - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// 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(); @@ -529,7 +541,7 @@ impl Index { "{}/indexes/{}/documents/{}", self.client.host, self.uid, uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -553,7 +565,7 @@ impl Index { /// # /// # futures::executor::block_on(async move { /// # - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movies = client.index("delete_documents"); /// /// // add some documents @@ -578,7 +590,7 @@ impl Index { "{}/indexes/{}/documents/delete-batch", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post(uids), 202, ) @@ -599,7 +611,7 @@ impl Index { /// /// # futures::executor::block_on(async move { /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let index = client.create_index("fetch_info", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// /// // get the information of the index named "fetch_info" @@ -625,7 +637,7 @@ impl Index { /// /// # futures::executor::block_on(async move { /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let index = client.create_index("get_primary_key", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// /// // get the primary key of the index named "movies" @@ -657,7 +669,7 @@ impl Index { /// # /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movies = client.index("get_task"); /// /// let task = movies.add_documents(&[ @@ -687,7 +699,7 @@ impl Index { self.uid, uid.as_ref() ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -703,7 +715,7 @@ impl Index { /// # use meilisearch_sdk::{client::*, indexes::*}; /// # /// # futures::executor::block_on(async move { - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let index = client.create_index("get_tasks", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap().try_make_index(&client).unwrap(); /// /// let status = index.get_tasks().await.unwrap(); @@ -724,7 +736,7 @@ impl Index { Ok(request::<(), AllTasks>( &format!("{}/indexes/{}/tasks", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -740,7 +752,7 @@ impl Index { /// # use meilisearch_sdk::{client::*, indexes::*}; /// # /// # futures::executor::block_on(async move { - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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(); @@ -751,7 +763,7 @@ impl Index { pub async fn get_stats(&self) -> Result { request::( &format!("{}/indexes/{}/stats", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -782,7 +794,7 @@ impl Index { /// # /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movies = client.index("movies_index_wait_for_task"); /// /// let task = movies.add_documents(&[ @@ -824,7 +836,7 @@ impl Index { /// } /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movie_index = client.index("add_documents_in_batches"); /// /// let tasks = movie_index.add_documents_in_batches(&[ @@ -885,7 +897,7 @@ impl Index { /// } /// /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movie_index = client.index("update_documents_in_batches"); /// /// let tasks = movie_index.add_documents_in_batches(&[ diff --git a/src/key.rs b/src/key.rs index 8b2b7cbd..af32ea63 100644 --- a/src/key.rs +++ b/src/key.rs @@ -44,7 +44,7 @@ impl AsRef for Key { /// ``` /// # use meilisearch_sdk::{key::KeyBuilder, key::Action, client::Client}; /// # futures::executor::block_on(async move { -/// let client = Client::new("http://localhost:7700", "masterKey"); +/// let client = Client::new("http://localhost:7700", Some("masterKey")); /// /// let key = KeyBuilder::new("My little lovely test key") /// .with_action(Action::DocumentsAdd) @@ -168,7 +168,7 @@ impl KeyBuilder { /// ``` /// # use meilisearch_sdk::{key::KeyBuilder, client::Client}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let key = KeyBuilder::new("My little lovely test key") /// .create(&client).await.unwrap(); /// diff --git a/src/lib.rs b/src/lib.rs index aaa6de00..4c79e459 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,7 +17,7 @@ //! //! fn main() { block_on(async move { //! // Create a client (without sending any request so that can't fail) -//! let client = Client::new("http://localhost:7700", "masterKey"); +//! let client = Client::new("http://localhost:7700", Some("masterKey")); //! //! # 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. @@ -51,7 +51,7 @@ //! # genres: Vec, //! # } //! # fn main() { block_on(async move { -//! # let client = Client::new("http://localhost:7700", "masterKey"); +//! # let client = Client::new("http://localhost:7700", Some("masterKey")); //! # 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); @@ -92,7 +92,7 @@ //! # genres: Vec, //! # } //! # fn main() { block_on(async move { -//! # let client = Client::new("http://localhost:7700", "masterKey"); +//! # let client = Client::new("http://localhost:7700", Some("masterKey")); //! # 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() @@ -137,7 +137,7 @@ //! # use serde::{Serialize, Deserialize}; //! # use futures::executor::block_on; //! # fn main() { block_on(async move { -//! # let client = Client::new("http://localhost:7700", "masterKey"); +//! # let client = Client::new("http://localhost:7700", Some("masterKey")); //! # 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,7 +165,7 @@ //! # genres: Vec, //! # } //! # fn main() { block_on(async move { -//! # let client = Client::new("http://localhost:7700", "masterKey"); +//! # let client = Client::new("http://localhost:7700", Some("masterKey")); //! # 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", diff --git a/src/request.rs b/src/request.rs index 52cd8d05..9d5b9f42 100644 --- a/src/request.rs +++ b/src/request.rs @@ -15,64 +15,116 @@ pub(crate) enum Method { #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn request( url: &str, - apikey: &str, + apikey: Option<&str>, method: Method, expected_status_code: u16, ) -> Result { use isahc::http::header; use isahc::*; - let auth = format!("Bearer {}", apikey); let user_agent = qualified_version(); let mut response = match &method { Method::Get => { - Request::get(url) - .header(header::AUTHORIZATION, auth) - .header(header::USER_AGENT, user_agent) - .body(()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? + if let Some(key) = apikey { + let auth = format!("Bearer {}", key); + Request::get(url) + .header(header::AUTHORIZATION, auth) + .header(header::USER_AGENT, user_agent) + .body(()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } else { + Request::get(url) + .header(header::USER_AGENT, user_agent) + .body(()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } } Method::Delete => { - Request::delete(url) - .header(header::AUTHORIZATION, auth) - .header(header::USER_AGENT, user_agent) - .body(()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? + if let Some(key) = apikey { + let auth = format!("Bearer {}", key); + Request::delete(url) + .header(header::AUTHORIZATION, auth) + .header(header::USER_AGENT, user_agent) + .body(()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } else { + Request::delete(url) + .header(header::USER_AGENT, user_agent) + .body(()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } } Method::Post(body) => { - Request::post(url) - .header(header::AUTHORIZATION, auth) - .header(header::CONTENT_TYPE, "application/json") - .header(header::USER_AGENT, user_agent) - .body(to_string(&body).unwrap()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? + if let Some(key) = apikey { + let auth = format!("Bearer {}", key); + Request::post(url) + .header(header::AUTHORIZATION, auth) + .header(header::CONTENT_TYPE, "application/json") + .header(header::USER_AGENT, user_agent) + .body(to_string(&body).unwrap()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } else { + Request::post(url) + .header(header::CONTENT_TYPE, "application/json") + .header(header::USER_AGENT, user_agent) + .body(to_string(&body).unwrap()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } } Method::Patch(body) => { - Request::patch(url) - .header(header::AUTHORIZATION, auth) - .header(header::CONTENT_TYPE, "application/json") - .header(header::USER_AGENT, user_agent) - .body(to_string(&body).unwrap()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? + if let Some(key) = apikey { + let auth = format!("Bearer {}", key); + Request::patch(url) + .header(header::AUTHORIZATION, auth) + .header(header::CONTENT_TYPE, "application/json") + .header(header::USER_AGENT, user_agent) + .body(to_string(&body).unwrap()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } else { + Request::patch(url) + .header(header::CONTENT_TYPE, "application/json") + .header(header::USER_AGENT, user_agent) + .body(to_string(&body).unwrap()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } } Method::Put(body) => { - Request::put(url) - .header(header::AUTHORIZATION, auth) - .header(header::CONTENT_TYPE, "application/json") - .header(header::USER_AGENT, user_agent) - .body(to_string(&body).unwrap()) - .map_err(|_| crate::errors::Error::InvalidRequest)? - .send_async() - .await? + if let Some(key) = apikey { + let auth = format!("Bearer {}", key); + Request::put(url) + .header(header::AUTHORIZATION, auth) + .header(header::CONTENT_TYPE, "application/json") + .header(header::USER_AGENT, user_agent) + .body(to_string(&body).unwrap()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } else { + Request::put(url) + .header(header::CONTENT_TYPE, "application/json") + .header(header::USER_AGENT, user_agent) + .body(to_string(&body).unwrap()) + .map_err(|_| crate::errors::Error::InvalidRequest)? + .send_async() + .await? + } } }; @@ -91,7 +143,7 @@ pub(crate) async fn request( url: &str, - apikey: &str, + apikey: &Option, method: Method, expected_status_code: u16, ) -> Result { @@ -106,7 +158,10 @@ pub(crate) async fn request = (&'a str, Option); /// /// ``` /// # use meilisearch_sdk::{client::Client, search::Query, indexes::Index}; -/// # let client = Client::new("http://localhost:7700", "masterKey"); +/// # let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let index = client.index("does not matter"); /// let query = Query::new(&index) /// .with_query("space") @@ -113,7 +113,7 @@ type AttributeToCrop<'a> = (&'a str, Option); /// /// ``` /// # use meilisearch_sdk::{client::Client, search::Query, indexes::Index}; -/// # let client = Client::new("http://localhost:7700", "masterKey"); +/// # let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let index = client.index("does not matter"); /// let query = index.search() /// .with_query("space") @@ -730,7 +730,7 @@ mod tests { .create(&client) .await .unwrap(); - let allowed_client = Client::new("http://localhost:7700", key.key); + let allowed_client = Client::new("http://localhost:7700", Option::from(key.key)); let search_rules = vec![ json!({ "*": {}}), @@ -744,7 +744,7 @@ mod tests { let token = allowed_client .generate_tenant_token(rules, None, None) .expect("Cannot generate tenant token."); - let new_client = Client::new("http://localhost:7700", token); + let new_client = Client::new("http://localhost:7700", Option::from(token)); let result: SearchResults = new_client .index(index.uid.to_string()) diff --git a/src/settings.rs b/src/settings.rs index 0344d021..b6a6fdd3 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -201,7 +201,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_settings", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_settings"); /// let settings = index.get_settings().await.unwrap(); @@ -211,7 +211,7 @@ impl Index { pub async fn get_settings(&self) -> Result { request::<(), Settings>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -223,7 +223,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_synonyms", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_synonyms"); /// let synonyms = index.get_synonyms().await.unwrap(); @@ -236,7 +236,7 @@ impl Index { "{}/indexes/{}/settings/synonyms", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -248,7 +248,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_stop_words", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_stop_words"); /// let stop_words = index.get_stop_words().await.unwrap(); @@ -261,7 +261,7 @@ impl Index { "{}/indexes/{}/settings/stop-words", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -273,7 +273,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_ranking_rules", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_ranking_rules"); /// let ranking_rules = index.get_ranking_rules().await.unwrap(); @@ -286,7 +286,7 @@ impl Index { "{}/indexes/{}/settings/ranking-rules", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -298,7 +298,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_filterable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_filterable_attributes"); /// let filterable_attributes = index.get_filterable_attributes().await.unwrap(); @@ -311,7 +311,7 @@ impl Index { "{}/indexes/{}/settings/filterable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -323,7 +323,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_sortable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_sortable_attributes"); /// let sortable_attributes = index.get_sortable_attributes().await.unwrap(); @@ -336,7 +336,7 @@ impl Index { "{}/indexes/{}/settings/sortable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -348,7 +348,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_distinct_attribute", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_distinct_attribute"); /// let distinct_attribute = index.get_distinct_attribute().await.unwrap(); @@ -361,7 +361,7 @@ impl Index { "{}/indexes/{}/settings/distinct-attribute", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -373,7 +373,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_searchable_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_searchable_attributes"); /// let searchable_attributes = index.get_searchable_attributes().await.unwrap(); @@ -386,7 +386,7 @@ impl Index { "{}/indexes/{}/settings/searchable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -398,7 +398,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("get_displayed_attributes", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let index = client.index("get_displayed_attributes"); /// let displayed_attributes = index.get_displayed_attributes().await.unwrap(); @@ -411,7 +411,7 @@ impl Index { "{}/indexes/{}/settings/displayed-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Get, 200, ) @@ -426,7 +426,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("set_settings", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_settings"); /// @@ -441,7 +441,7 @@ impl Index { pub async fn set_settings(&self, settings: &Settings) -> Result { request::<&Settings, Task>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post(settings), 202, ) @@ -455,7 +455,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("set_synonyms", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("set_synonyms"); /// @@ -477,7 +477,7 @@ impl Index { "{}/indexes/{}/settings/synonyms", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post(synonyms), 202, ) @@ -491,7 +491,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -509,7 +509,7 @@ impl Index { "{}/indexes/{}/settings/stop-words", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post( stop_words .into_iter() @@ -528,7 +528,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -555,7 +555,7 @@ impl Index { "{}/indexes/{}/settings/ranking-rules", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post( ranking_rules .into_iter() @@ -574,7 +574,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -592,7 +592,7 @@ impl Index { "{}/indexes/{}/settings/filterable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post( filterable_attributes .into_iter() @@ -611,7 +611,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -629,7 +629,7 @@ impl Index { "{}/indexes/{}/settings/sortable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post( sortable_attributes .into_iter() @@ -648,7 +648,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -665,7 +665,7 @@ impl Index { "{}/indexes/{}/settings/distinct-attribute", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post(distinct_attribute.as_ref().to_string()), 202, ) @@ -679,7 +679,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -696,7 +696,7 @@ impl Index { "{}/indexes/{}/settings/searchable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post( searchable_attributes .into_iter() @@ -715,7 +715,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -732,7 +732,7 @@ impl Index { "{}/indexes/{}/settings/displayed-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Post( displayed_attributes .into_iter() @@ -752,7 +752,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("reset_settings", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_settings"); /// @@ -763,7 +763,7 @@ impl Index { pub async fn reset_settings(&self) -> Result { request::<(), Task>( &format!("{}/indexes/{}/settings", self.client.host, self.uid), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -777,7 +777,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # client.create_index("reset_synonyms", None).await.unwrap().wait_for_completion(&client, None, None).await.unwrap(); /// let mut index = client.index("reset_synonyms"); /// @@ -791,7 +791,7 @@ impl Index { "{}/indexes/{}/settings/synonyms", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -805,7 +805,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -819,7 +819,7 @@ impl Index { "{}/indexes/{}/settings/stop-words", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -834,7 +834,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -848,7 +848,7 @@ impl Index { "{}/indexes/{}/settings/ranking-rules", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -862,7 +862,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -876,7 +876,7 @@ impl Index { "{}/indexes/{}/settings/filterable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -890,7 +890,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -904,7 +904,7 @@ impl Index { "{}/indexes/{}/settings/sortable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -918,7 +918,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -932,7 +932,7 @@ impl Index { "{}/indexes/{}/settings/distinct-attribute", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -946,7 +946,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -960,7 +960,7 @@ impl Index { "{}/indexes/{}/settings/searchable-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) @@ -974,7 +974,7 @@ impl Index { /// ``` /// # use meilisearch_sdk::{client::*, indexes::*, settings::Settings}; /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # 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"); /// @@ -988,7 +988,7 @@ impl Index { "{}/indexes/{}/settings/displayed-attributes", self.client.host, self.uid ), - &self.client.api_key, + self.client.api_key.as_deref(), Method::Delete, 202, ) diff --git a/src/tasks.rs b/src/tasks.rs index eb4588b5..2fbbd6d4 100644 --- a/src/tasks.rs +++ b/src/tasks.rs @@ -168,7 +168,7 @@ impl Task { /// # /// # /// # futures::executor::block_on(async move { - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let movies = client.index("movies_wait_for_completion"); /// /// let status = movies.add_documents(&[ @@ -205,7 +205,7 @@ impl Task { /// # /// # futures::executor::block_on(async move { /// // create the client - /// let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// /// 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(); @@ -239,7 +239,7 @@ impl Task { /// # use meilisearch_sdk::{client::*, indexes::*, errors::ErrorCode}; /// # /// # futures::executor::block_on(async move { - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let task = client.create_index("unwrap_failure", None).await.unwrap(); /// # let index = client.wait_for_task(task, None, None).await.unwrap().try_make_index(&client).unwrap(); /// @@ -276,7 +276,7 @@ impl Task { /// # use meilisearch_sdk::{client::*, indexes::*, errors::ErrorCode}; /// # /// # futures::executor::block_on(async move { - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// # let task = client.create_index("is_failure", None).await.unwrap(); /// # let index = client.wait_for_task(task, None, None).await.unwrap().try_make_index(&client).unwrap(); /// @@ -303,7 +303,7 @@ impl Task { /// # use meilisearch_sdk::{client::*, indexes::*, errors::ErrorCode}; /// # /// # futures::executor::block_on(async move { - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let task = client /// .create_index("is_success", None) /// .await @@ -327,7 +327,7 @@ impl Task { /// # use meilisearch_sdk::{client::*, indexes::*, errors::ErrorCode}; /// # /// # futures::executor::block_on(async move { - /// # let client = Client::new("http://localhost:7700", "masterKey"); + /// let client = Client::new("http://localhost:7700", Some("masterKey")); /// let task = client /// .create_index("is_pending", None) /// .await diff --git a/src/tenant_tokens.rs b/src/tenant_tokens.rs index 369f401b..113d2777 100644 --- a/src/tenant_tokens.rs +++ b/src/tenant_tokens.rs @@ -1,13 +1,11 @@ -use crate::{ - errors::* -}; -use serde::{Serialize, Deserialize}; -use jsonwebtoken::{encode, Header, EncodingKey}; -use time::{OffsetDateTime}; +use crate::errors::*; +use jsonwebtoken::{encode, EncodingKey, Header}; +use serde::{Deserialize, Serialize}; use serde_json::Value; +use time::OffsetDateTime; #[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase")] struct TenantTokenClaim { api_key_prefix: String, search_rules: Value, @@ -15,20 +13,24 @@ struct TenantTokenClaim { exp: Option, } -pub fn generate_tenant_token(search_rules: Value, api_key: impl AsRef, expires_at: Option) -> Result { +pub fn generate_tenant_token( + search_rules: Value, + api_key: impl AsRef, + expires_at: Option, +) -> Result { if api_key.as_ref().chars().count() < 8 { - return Err(Error::TenantTokensInvalidApiKey) + return Err(Error::TenantTokensInvalidApiKey); } if expires_at.map_or(false, |expires_at| OffsetDateTime::now_utc() > expires_at) { - return Err(Error::TenantTokensExpiredSignature) + return Err(Error::TenantTokensExpiredSignature); } let key_prefix = api_key.as_ref().chars().take(8).collect(); let claims = TenantTokenClaim { api_key_prefix: key_prefix, exp: expires_at, - search_rules + search_rules, }; let token = encode( @@ -42,9 +44,9 @@ pub fn generate_tenant_token(search_rules: Value, api_key: impl AsRef, expi #[cfg(test)] mod tests { - use serde_json::json; use crate::tenant_tokens::*; - use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; + use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; + use serde_json::json; use std::collections::HashSet; const SEARCH_RULES: [&str; 1] = ["*"]; @@ -63,10 +65,14 @@ mod tests { let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, None).unwrap(); let valid_key = decode::( - &token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &build_validation() + &token, + &DecodingKey::from_secret(VALID_KEY.as_ref()), + &build_validation(), ); let invalid_key = decode::( - &token, &DecodingKey::from_secret("not-the-same-key".as_ref()), &build_validation() + &token, + &DecodingKey::from_secret("not-the-same-key".as_ref()), + &build_validation(), ); assert!(valid_key.is_ok()); @@ -87,7 +93,9 @@ mod tests { let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, Some(exp)).unwrap(); let decoded = decode::( - &token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &Validation::new(Algorithm::HS256) + &token, + &DecodingKey::from_secret(VALID_KEY.as_ref()), + &Validation::new(Algorithm::HS256), ); assert!(decoded.is_ok()); @@ -106,8 +114,11 @@ mod tests { let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, None).unwrap(); let decoded = decode::( - &token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &build_validation() - ).expect("Cannot decode the token"); + &token, + &DecodingKey::from_secret(VALID_KEY.as_ref()), + &build_validation(), + ) + .expect("Cannot decode the token"); assert_eq!(decoded.claims.api_key_prefix, &VALID_KEY[..8]); assert_eq!(decoded.claims.search_rules, json!(SEARCH_RULES)); @@ -119,8 +130,11 @@ mod tests { let token = generate_tenant_token(json!(SEARCH_RULES), key, None).unwrap(); let decoded = decode::( - &token, &DecodingKey::from_secret(key.as_ref()), &build_validation() - ).expect("Cannot decode the token"); + &token, + &DecodingKey::from_secret(key.as_ref()), + &build_validation(), + ) + .expect("Cannot decode the token"); assert_eq!(decoded.claims.api_key_prefix, "Ëa1ทt9bV"); }