Skip to content

Commit a081c7a

Browse files
committed
Rename: collection() requires trait Document
1 parent 0070ab2 commit a081c7a

File tree

10 files changed

+155
-62
lines changed

10 files changed

+155
-62
lines changed

typesense/src/client/collection/document.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,26 @@
22
//!
33
//! An instance of `Document` is scoped to a specific document and is created
44
//! via a parent `Collection` struct, for example:
5-
//! `client.collection::<Book>("books").document("123")`
5+
//! `client.collection::<Book>().document("123")`
66
77
use crate::{Client, Error, execute_wrapper};
88
use serde::{Serialize, de::DeserializeOwned};
99
use typesense_codegen::apis::documents_api;
1010

1111
/// Provides methods for interacting with a single document within a specific Typesense collection.
1212
///
13-
/// This struct is created by calling a method like `client.collection("collection_name").document("document_id")` or `client.collection_of::<MyType>("collection_name").document("document_id")`.
13+
/// This struct is created by calling a method like `client.collection_schemaless("collection_name").document("document_id")`
14+
/// or `client.collection::<MyType>().document("document_id")`.
1415
/// The generic `T` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`.
1516
/// If `T` is not specified, it defaults to `serde_json::Value` for schemaless interactions.
1617
pub struct Document<'c, 'n, D = serde_json::Value>
1718
where
1819
D: DeserializeOwned + Serialize + Send + Sync,
1920
{
20-
pub(super) client: &'c Client,
21-
pub(super) collection_name: &'n str,
22-
pub(super) document_id: String,
23-
pub(super) _phantom: std::marker::PhantomData<D>,
21+
client: &'c Client,
22+
collection_name: &'n str,
23+
document_id: String,
24+
_phantom: std::marker::PhantomData<D>,
2425
}
2526

2627
impl<'c, 'n, D> Document<'c, 'n, D>
@@ -81,15 +82,15 @@ where
8182
/// let book_update = serde_json::json!({ "pages": 654 });
8283
///
8384
/// // Simple update
84-
/// let updated_book = client.collection_of::<Book>("books").document("123")
85+
/// let updated_book = client.collection_named::<Book>("books").document("123")
8586
/// .update(&book_update, None)
8687
/// .await?;
8788
///
8889
/// // Update with additional parameters
8990
/// let params = models::DocumentIndexParameters {
9091
/// dirty_values: Some(models::DirtyValues::CoerceOrReject),
9192
/// };
92-
/// let updated_book_with_params = client.collection_of::<Book>("books").document("124")
93+
/// let updated_book_with_params = client.collection_named::<Book>("books").document("124")
9394
/// .update(&book_update, Some(params))
9495
/// .await?;
9596
/// #

typesense/src/client/collection/documents.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
//! Provides access to the document, search, and override-related API endpoints.
22
//!
33
//! An instance of `Documents` is scoped to a specific collection and is created
4-
//! via the main `client.collection("collection_name").documents()` method or
5-
//! `client.collection_of::<T>("...").documents()`.
4+
//! via the main `client.collection_schemaless("collection_name").documents()` method or
5+
//! `client.collection_named::<T>("...").documents()`.
66
77
use crate::{
88
Client, Error, execute_wrapper,
@@ -18,16 +18,16 @@ use typesense_codegen::{
1818
};
1919
/// Provides methods for interacting with documents within a specific Typesense collection.
2020
///
21-
/// This struct is generic over the document type `T`. If created via `client.collection(...)`,
22-
/// `T` defaults to `serde_json::Value`. If created via `client.collection_of::<MyType>(...)`,
21+
/// This struct is generic over the document type `T`. If created via `client.collection_schemaless(...)`,
22+
/// `T` defaults to `serde_json::Value`. If created via `client.collection_named::<MyType>(...)`,
2323
/// `T` will be `MyType`.
2424
pub struct Documents<'c, 'n, D = serde_json::Value>
2525
where
2626
D: DeserializeOwned + Serialize + Send + Sync,
2727
{
28-
pub(super) client: &'c Client,
29-
pub(super) collection_name: &'n str,
30-
pub(super) _phantom: std::marker::PhantomData<D>,
28+
client: &'c Client,
29+
collection_name: &'n str,
30+
_phantom: std::marker::PhantomData<D>,
3131
}
3232

3333
impl<'c, 'n, D> Documents<'c, 'n, D>
@@ -85,7 +85,7 @@ where
8585
/// Creates a new document or updates an existing one if an ID match is found.
8686
///
8787
/// This method requires the full document to be sent. For partial updates, use
88-
/// `collection("...").document("...").update()`. The indexed document is returned.
88+
/// `collection().document("...").update()`. The indexed document is returned.
8989
///
9090
/// # Arguments
9191
/// * `document` - A serializable struct or a `serde_json::Value` representing the document to upsert.

typesense/src/client/collection/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@ use typesense_codegen::{apis::collections_api, models};
1111

1212
/// Provides methods for interacting with a Typesense collection.
1313
///
14-
/// This struct is created by calling `client.collection("collection_name")`.
14+
/// This struct is created by calling `client.collection()`.
1515
pub struct Collection<'c, 'n, D = serde_json::Value>
1616
where
1717
D: DeserializeOwned + Serialize + Send + Sync,
1818
{
19-
pub(super) client: &'c Client,
20-
pub(super) collection_name: &'n str,
21-
pub(super) _phantom: std::marker::PhantomData<D>,
19+
client: &'c Client,
20+
collection_name: &'n str,
21+
_phantom: std::marker::PhantomData<D>,
2222
}
2323

2424
impl<'c, 'n, D> Collection<'c, 'n, D>

typesense/src/client/mod.rs

Lines changed: 57 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
//! .unwrap();
3434
//!
3535
//! // Retrieve details for a collection
36-
//! let collection = client.collection("products").retrieve().await?;
36+
//! let collection = client.collection_schemaless("products").retrieve().await?;
3737
//! println!("Collection Name: {}", collection.name);
3838
//!
3939
//! // Search for a document
@@ -44,7 +44,7 @@
4444
//! };
4545
//!
4646
//! let search_results = client
47-
//! .collection("products")
47+
//! .collection_schemaless("products")
4848
//! .documents()
4949
//! .search(search_params)
5050
//! .await?;
@@ -84,7 +84,7 @@
8484
//! .unwrap();
8585
//!
8686
//! // Retrieve details for a collection
87-
//! match client.collection("products").retrieve().await {
87+
//! match client.collection_schemaless("products").retrieve().await {
8888
//! Ok(collection) => println!("Collection Name: {}", collection.name),
8989
//! Err(e) => eprintln!("Error retrieving collection: {}", e),
9090
//! }
@@ -96,7 +96,7 @@
9696
//! ..Default::default()
9797
//! };
9898
//!
99-
//! match client.collection("products").documents().search(search_params).await {
99+
//! match client.collection_schemaless("products").documents().search(search_params).await {
100100
//! Ok(search_results) => {
101101
//! println!("Found {} hits.", search_results.found.unwrap_or(0));
102102
//! }
@@ -112,7 +112,7 @@ mod key;
112112
mod keys;
113113
mod multi_search;
114114

115-
use crate::Error;
115+
use crate::{Error, traits::Document};
116116
use collection::Collection;
117117
use collections::Collections;
118118
use key::Key;
@@ -392,7 +392,7 @@ impl Client {
392392
/// # .build()
393393
/// # .unwrap();
394394
/// // Get a typed handle to the "books" collection
395-
/// let books_collection = client.collection_of::<Book>("books");
395+
/// let books_collection = client.collection_named::<Book>("books");
396396
///
397397
/// // Retrieve a single book, it returns `Result<Book, ...>`
398398
/// let book = books_collection.document("123").retrieve().await?;
@@ -403,17 +403,62 @@ impl Client {
403403
/// # }
404404
/// ```
405405
#[inline]
406-
pub fn collection_of<'c, 'n, T>(&'c self, collection_name: &'n str) -> Collection<'c, 'n, T>
406+
pub fn collection_named<'c, 'n, D>(&'c self, collection_name: &'n str) -> Collection<'c, 'n, D>
407407
where
408-
T: DeserializeOwned + Serialize + Send + Sync,
408+
D: DeserializeOwned + Serialize + Send + Sync,
409409
{
410410
Collection::new(self, collection_name)
411411
}
412412

413+
/// Provides access to API endpoints for a specific collection.
414+
///
415+
/// This method returns a `Collection<T>` handle, which is generic over the type of document
416+
/// stored in that collection.
417+
///
418+
/// # Type Parameters
419+
/// * `T` - The type of the documents in the collection. It must be of trait Document.
420+
///
421+
/// # Example: Working with a strongly-typed collection
422+
///
423+
/// When you want to retrieve or search for documents and have them automatically
424+
/// deserialized into your own structs.
425+
/// ```no_run
426+
/// # #[cfg(not(target_family = "wasm"))]
427+
/// # {
428+
/// # use typesense::Client;
429+
/// # use serde::{Serialize, Deserialize};
430+
/// #
431+
/// # #[derive(Serialize, Deserialize, Debug)]
432+
/// # struct Book { id: String, title: String }
433+
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
434+
/// # let client = Client::builder()
435+
/// # .nodes(vec!["http://localhost:8108"])
436+
/// # .api_key("xyz")
437+
/// # .build()
438+
/// # .unwrap();
439+
/// // Get a typed handle to the "books" collection
440+
/// let books_collection = client.collection::<Book>();
441+
///
442+
/// // Retrieve a single book, it returns `Result<Book, ...>`
443+
/// let book = books_collection.document("123").retrieve().await?;
444+
/// println!("Retrieved book: {:?}", book);
445+
/// #
446+
/// # Ok(())
447+
/// # }
448+
/// # }
449+
/// ```
450+
#[inline]
451+
pub fn collection<'c, 'n, D>(&'c self) -> Collection<'c, 'n, D>
452+
where
453+
D: Document + Send + Sync,
454+
{
455+
Collection::new(self, D::COLLECTION_NAME)
456+
}
457+
413458
/// Provides access to API endpoints for a specific collection using schemaless `serde_json::Value` documents.
414459
///
415460
/// This is the simplest way to interact with a collection when you do not need strong typing.
416-
/// It is a convenient shorthand for `client.collection_of::<serde_json::Value>("...")`.
461+
/// It is a convenient shorthand for `client.collection_named::<serde_json::Value>("...")`.
417462
///
418463
/// The returned handle can be used for both document operations (which will return `serde_json::Value`)
419464
/// and collection-level operations (like `.delete()` or `.retrieve()`).
@@ -432,18 +477,18 @@ impl Client {
432477
/// # .api_key("xyz")
433478
/// # .build()
434479
/// # .unwrap();
435-
/// let products_collection = client.collection("products");
480+
/// let products_collection = client.collection_schemaless("products");
436481
/// #
437482
/// # Ok(())
438483
/// # }
439484
/// # }
440485
/// ```
441486
#[inline]
442-
pub fn collection<'c, 'n>(
487+
pub fn collection_schemaless<'c, 'n>(
443488
&'c self,
444489
collection_name: &'n str,
445490
) -> Collection<'c, 'n, serde_json::Value> {
446-
self.collection_of(collection_name)
491+
Collection::new(self, collection_name)
447492
}
448493

449494
/// Provides access to endpoints for managing the collection of API keys.

typesense/src/traits/document.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ use serde::{Serialize, de::DeserializeOwned};
99
/// Trait that should implement every struct that wants to be represented as a Typesense
1010
/// Document
1111
pub trait Document: DeserializeOwned + Serialize {
12+
/// Collection name
13+
const COLLECTION_NAME: &'static str;
14+
1215
/// Collection schema associated with the document.
1316
fn collection_schema() -> CollectionSchema;
1417
}

0 commit comments

Comments
 (0)