firestore-manager

Crates.iofirestore-manager
lib.rsfirestore-manager
version0.1.0
created_at2026-01-16 09:20:11.123192+00
updated_at2026-01-16 09:20:11.123192+00
descriptionA comprehensive Rust library for managing Google Cloud Firestore
homepage
repositoryhttps://github.com/yourusername/firestore-manager
max_upload_size
id2048298
size182,623
(Pick999999)

documentation

README

🔥 Firestore Manager

Rust library สำหรับจัดการ Google Cloud Firestore อย่างง่ายและมีประสิทธิภาพ พร้อมฟังก์ชันครบครันสำหรับการทำงานกับ Firestore

✨ Features

  • ✅ เชื่อมต่อกับ Google Cloud Firestore
  • 📚 แสดงรายชื่อ Collections ทั้งหมด
  • 📖 อ่านข้อมูลจาก Collection
  • ➕ เพิ่มข้อมูลใหม่ (Auto-generated ID หรือ Custom ID)
  • 🔄 อัพเดทข้อมูลแบบเต็ม Document
  • 🔧 อัพเดทเฉพาะ Fields ที่ต้องการ
  • 🗑️ ลบข้อมูล
  • 🔍 ค้นหา Document ด้วย ID
  • 🛡️ Type-safe ด้วย Serde serialization
  • 🚀 Async/Await support ด้วย Tokio
  • ⚠️ Custom error handling

📋 Prerequisites

  1. Google Cloud Project: คุณต้องมี Google Cloud Project ที่เปิดใช้งาน Firestore
  2. Service Account: สร้าง Service Account และดาวน์โหลด JSON key file
  3. Environment Variable: ตั้งค่า GOOGLE_APPLICATION_CREDENTIALS ให้ชี้ไปที่ JSON key file
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"

📦 Installation

เพิ่ม dependency ใน Cargo.toml:

[dependencies]
firestore-manager = "0.1.0"
tokio = { version = "1.35", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }

🚀 Quick Start

1. การเชื่อมต่อกับ Firestore

use firestore_manager::FirestoreManager;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let manager = FirestoreManager::new("your-project-id").await?;
    Ok(())
}

2. สร้าง Struct สำหรับข้อมูล

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    email: String,
    age: u32,
}

3. แสดงรายชื่อ Collections ทั้งหมด

let collections = manager.list_collections().await?;
for collection in collections {
    println!("Collection: {}", collection);
}

4. เพิ่มข้อมูลใหม่

Auto-generated ID

let user = User {
    name: "John Doe".to_string(),
    email: "john@example.com".to_string(),
    age: 30,
};

let doc_id = manager.add_document("users", None, &user).await?;
println!("Document ID: {}", doc_id);

Custom ID

let doc_id = manager.add_document("users", Some("user_123"), &user).await?;

5. อ่านข้อมูลทั้ง Collection

let users: Vec<(String, User)> = manager.get_collection("users").await?;
for (id, user) in users {
    println!("ID: {} -> Name: {}", id, user.name);
}

6. อ่านข้อมูล Document เฉพาะ

let user: User = manager.get_document("users", "user_123").await?;
println!("User: {:?}", user);

7. อัพเดทข้อมูลทั้ง Document

let updated_user = User {
    name: "Jane Doe".to_string(),
    email: "jane@example.com".to_string(),
    age: 28,
};

manager.update_document("users", "user_123", &updated_user).await?;

8. อัพเดทเฉพาะ Fields

use std::collections::HashMap;

let mut fields = HashMap::new();
fields.insert("email".to_string(), serde_json::json!("newemail@example.com"));
fields.insert("age".to_string(), serde_json::json!(31));

manager.update_fields("users", "user_123", fields).await?;

9. ลบ Document

manager.delete_document("users", "user_123").await?;

📖 Complete Example

ดู examples/basic_usage.rs สำหรับตัวอย่างการใช้งานแบบครบถ้วน:

# ตั้งค่า environment variables
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"
export GOOGLE_CLOUD_PROJECT="your-project-id"

# รัน example
cargo run --example basic_usage

🏗️ Project Structure

firestore-manager/
├── Cargo.toml
├── README.md
├── src/
│   └── lib.rs          # Main library code
└── examples/
    └── basic_usage.rs  # Usage examples

🔧 API Reference

FirestoreManager

new(project_id: &str) -> Result<Self, FirestoreError>

สร้าง instance ใหม่ของ FirestoreManager

list_collections() -> Result<Vec<String>, FirestoreError>

แสดงรายชื่อ collections ทั้งหมดในระดับ root

get_collection<T>(collection_name: &str) -> Result<Vec<(String, T)>, FirestoreError>

ดึงข้อมูลทั้งหมดจาก collection โดยคืนค่าเป็น Vec ของ (document_id, data)

add_document<T>(collection_name: &str, document_id: Option<&str>, data: &T) -> Result<String, FirestoreError>

เพิ่ม document ใหม่ คืนค่า document ID

update_document<T>(collection_name: &str, document_id: &str, data: &T) -> Result<(), FirestoreError>

อัพเดท document ทั้งหมด

update_fields(collection_name: &str, document_id: &str, fields: HashMap<String, Value>) -> Result<(), FirestoreError>

อัพเดทเฉพาะ fields ที่ระบุ

delete_document(collection_name: &str, document_id: &str) -> Result<(), FirestoreError>

ลบ document

get_document<T>(collection_name: &str, document_id: &str) -> Result<T, FirestoreError>

ดึงข้อมูล document เฉพาะด้วย ID

⚠️ Error Handling

Library ใช้ custom error type FirestoreError:

match manager.get_document::<User>("users", "user_123").await {
    Ok(user) => println!("Found: {:?}", user),
    Err(FirestoreError::DocumentNotFound(id)) => {
        println!("Document {} not found", id);
    }
    Err(e) => println!("Error: {}", e),
}

Error types ที่รองรับ:

  • ConnectionError - ปัญหาการเชื่อมต่อ
  • CollectionNotFound - ไม่พบ collection
  • DocumentNotFound - ไม่พบ document
  • SerializationError - ปัญหาการ serialize/deserialize
  • OperationFailed - การทำงานล้มเหลว

🔐 Authentication

Library รองรับการ authentication ผ่าน:

  1. Service Account Key (แนะนำ):
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"
  1. Application Default Credentials: จะใช้ credentials จาก gcloud CLI โดยอัตโนมัติ

🧪 Testing

# Run tests
cargo test

# Run with logging
RUST_LOG=debug cargo test

# Run specific example
cargo run --example basic_usage

📝 Best Practices

  1. ใช้ Type Safety: กำหนด struct ด้วย Serialize และ Deserialize เสมอ
  2. Handle Errors: ใช้ Result และ handle errors อย่างเหมาะสม
  3. Connection Reuse: สร้าง FirestoreManager instance เพียงครั้งเดียวและใช้ซ้ำ
  4. Async Runtime: ใช้ tokio runtime สำหรับ async operations
  5. Environment Variables: เก็บ sensitive data เช่น project ID ใน environment variables

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the MIT License.

🔗 Resources

📞 Support

หากพบปัญหาหรือมีคำถาม:

  • เปิด issue ใน GitHub repository
  • ดูเอกสารประกอบใน examples/ directory

Made with ❤️ for the Rust community

Commit count: 0

cargo fmt