Skip to content

Commit

Permalink
Add Client::collection
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed Nov 3, 2023
1 parent 4f6454f commit db70119
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
16 changes: 12 additions & 4 deletions rust/crates/web/src/infra/firestore.rs
Expand Up @@ -5,15 +5,23 @@ pub mod timestamp;

#[cfg(test)]
mod tests {
use crate::infra::firestore::{client::Client, document::Document, path::RootPath};
use crate::infra::firestore::{client::Client, document::Document};

#[tokio::test]
async fn test() -> anyhow::Result<()> {
let endpoint = "http://firebase:8080";
let root_path = RootPath::new("demo-project1".to_string(), "(default)".to_string())?;
let collection_path = root_path.collection("repositories".to_string());
let mut client = Client::new(
"demo-project1".to_string(),
"(default)".to_string(),
endpoint,
)
.await?;
let collection_path = client.collection("repositories".to_string());

let mut client = Client::new(endpoint).await?;
assert_eq!(
collection_path.path(),
"projects/demo-project1/databases/(default)/documents/repositories"
);

// reset
let (documents, _) = client.list::<V>(&collection_path).await?;
Expand Down
18 changes: 15 additions & 3 deletions rust/crates/web/src/infra/firestore/client.rs
Expand Up @@ -13,7 +13,7 @@ use crate::infra::firestore::document;

use super::{
document::Document,
path::{CollectionPath, DocumentPath},
path::{self, CollectionPath, DocumentPath, RootPath},
timestamp::Timestamp,
};

Expand All @@ -23,6 +23,8 @@ pub enum Error {
Credentials(#[from] google_authz::CredentialsError),
#[error("deserialize {0}")]
Deserialize(#[from] document::Error),
#[error("path {0}")]
Path(#[from] path::Error),
#[error("serialize {0}")]
Serialize(#[from] serde_firestore_value::Error),
#[error("status {0}")]
Expand All @@ -35,6 +37,7 @@ pub enum Error {

pub struct Client {
client: FirestoreClient<GoogleAuthz<Channel>>,
root_path: RootPath,
}

impl Client {
Expand All @@ -43,15 +46,24 @@ impl Client {
// TODO: rollback
// TODO: run_query

pub async fn new(endpoint: &'static str) -> Result<Self, Error> {
pub async fn new(
project_id: String,
database_id: String,
endpoint: &'static str,
) -> Result<Self, Error> {
let credentials = Credentials::builder().no_credentials().build().await?;
let channel = Channel::from_static(endpoint).connect().await?;
let channel = GoogleAuthz::builder(channel)
.credentials(credentials)
.build()
.await;
let client = FirestoreClient::new(channel);
Ok(Self { client })
let root_path = RootPath::new(project_id, database_id)?;
Ok(Self { client, root_path })
}

pub fn collection(&self, collection_id: String) -> CollectionPath {
self.root_path.clone().collection(collection_id)
}

pub async fn create<T, U>(
Expand Down

0 comments on commit db70119

Please sign in to comment.