Skip to content

Commit

Permalink
Initial firebase-firestore-ktx
Browse files Browse the repository at this point in the history
  • Loading branch information
parkwoocheol committed Nov 19, 2024
1 parent 3b1d769 commit c4da086
Show file tree
Hide file tree
Showing 17 changed files with 947 additions and 0 deletions.
46 changes: 46 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Built application files
*.apk
*.ap_
*.aab

# Files for the ART/Dalvik VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Log Files
*.log

# Android Studio Navigation editor temp files
.navigation/

# Android Studio captures folder
captures/

# IntelliJ
*.iml
.idea
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
.idea/caches
.idea/modules.xml

# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
197 changes: 197 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
# Firebase Firestore KTX

Type-safe Kotlin extensions for Firebase Firestore with enhanced Flow support.

[![](https://jitpack.io/v/parkwoocheol/firebase-firestore-ktx.svg)](https://jitpack.io/#parkwoocheol/firebase-firestore-ktx)
[![Kotlin](https://img.shields.io/badge/kotlin-1.9.22-blue.svg?logo=kotlin)](http://kotlinlang.org)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0)

## Features 🚀

- 💫 Enhanced Firebase KTX extensions with FirestoreResult wrapper
- 🔄 Improved Flow support with integrated error handling
- 📦 Consistent Loading, Success, and Error states
- 🎯 Type-safe property references for queries
- 🔁 Automatic retry support for transactions

## Installation 📦

Add the JitPack repository and include the library:

```kotlin
// settings.gradle.kts
dependencyResolutionManagement {
repositories {
maven("https://jitpack.io")
}
}

// build.gradle.kts (app level)
dependencies {
implementation("com.github.parkwoocheol:firebase-firestore-ktx:1.0.0")
}
```

Note: Replace `1.0.0` with the latest version from the JitPack badge above.

## Usage Guide 🔥

### 1. Data Models

```kotlin
data class Developer(
@DocumentId override val id: String = "",
val name: String,
val email: String,
val role: String,
@ServerTimestamp
val createdAt: Timestamp? = null
) : FirestoreDocument
```

### 2. Real-time Document Updates

```kotlin
// Using enhanced dataObjects with state handling
developerRef.dataObjectsWithState<Developer>()
.onEach { result ->
when (result) {
is FirestoreResult.Success -> {
val developer = result.data
updateUI(developer)
}
is FirestoreResult.Error -> {
// Direct access to Throwable
handleError(result.throwable)
}
FirestoreResult.Loading -> showLoading()
}
}
.collect()

// Using enhanced snapshots
developerRef.snapshotsWithState()
.onEach { result ->
when (result) {
is FirestoreResult.Success -> handleSnapshot(result.data)
is FirestoreResult.Error -> handleError(result.throwable)
FirestoreResult.Loading -> showLoading()
}
}
.collect()
```

### 3. Query Operations

```kotlin
// Type-safe queries with real-time updates
developersRef
.whereEqualTo(Developer::role, "senior")
.whereGreaterThan(Developer::experience, 5)
.orderByDesc(Developer::createdAt)
.dataObjectsWithState<Developer>()
.collect { result ->
when (result) {
is FirestoreResult.Success -> updateList(result.data)
is FirestoreResult.Error -> handleError(result.throwable)
FirestoreResult.Loading -> showLoading()
}
}
```

### 4. Transactions

```kotlin
firestore.runTransactionWithRetry { transaction ->
// Get current data
val developerResult = transaction.getData<User>(userRef)

developerResult.onSuccess { developer ->
// Update developer profile
transaction.setData(userRef, developer.copy(
role = "senior developer",
lastPromoted = Timestamp.now()
))
}
}
```

### 5. Batch Operations

```kotlin
// DSL-style batch operations
firestore.batch {
set(parkRef, Developer(
name = "Woocheol Park",
role = "senior"
))
update(kimRef, mapOf("role" to "lead"))
delete(leeRef)
}

// Multiple document updates
val updates = mapOf(
parkRef to Developer(name = "Woocheol Park", role = "senior"),
kimRef to Developer(name = "Minsoo Kim", role = "junior")
)
firestore.batchSet(updates, merge = true)
.onSuccess { /* handle success */ }
.onError { throwable -> handleError(throwable) }
```

### 6. Error Handling

```kotlin
// Using extension functions with Flow error handling
developerRef.dataObjectsWithState<Developer>()
.onEach { result ->
when (result) {
is FirestoreResult.Success -> {
result.data?.let { developer ->
updateUI(developer)
} ?: showEmpty()
}
is FirestoreResult.Error -> {
when (val throwable = result.throwable) {
is FirebaseFirestoreException -> handleFirestoreError(throwable)
else -> handleGeneralError(throwable)
}
}
FirestoreResult.Loading -> showLoading()
}
}
.catch { throwable ->
// Handle Flow collection errors
handleFlowError(throwable)
}
.collect()
```

### 7. ProGuard Rules

If you're using ProGuard, add these rules to your `proguard-rules.pro`:

```proguard
# Firebase Models
-keepclassmembers class com.your.package.models.** {
*;
}
```

## License 📄

```
Copyright 2024 Woocheol Park
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
69 changes: 69 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.jetbrains.kotlin.android)
id("maven-publish")
}

android {
namespace = "com.parkwoocheol.firebase.firestore.ktx"
compileSdk = 34

defaultConfig {
minSdk = 21
}

buildTypes {
release {
isMinifyEnabled = false
}
}

compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}

kotlinOptions {
jvmTarget = JavaVersion.VERSION_17.toString()
}
}

dependencies {
implementation(platform(libs.firebase.bom))
api(libs.firebase.firestore)
implementation(libs.coroutines.android)
}


afterEvaluate {
publishing {
publications {
create<MavenPublication>("release") {
from(components["release"])

groupId = "com.github.parkwoocheol"
artifactId = "firebase-firestore-ktx"
version = "1.0.0"

pom {
name.set("Firebase Firestore KTX")
description.set("Type-safe Kotlin extensions for Firebase Firestore with coroutines support")
url.set("https://github.com/parkwoocheol/firebase-firestore-ktx")

licenses {
license {
name.set("The Apache License, Version 2.0")
url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
}
}
developers {
developer {
id.set("parkwoocheol")
name.set("Woocheol Park")
}
}
}
}
}
}
}
23 changes: 23 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
14 changes: 14 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[versions]
agp = "8.5.2"
kotlin = "1.9.22"
coroutines = "1.9.0"
firebase-bom = "33.6.0"

[libraries]
coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebase-bom" }
firebase-firestore = { group = "com.google.firebase", name = "firebase-firestore" }

[plugins]
android-library = { id = "com.android.library", version.ref = "agp" }
jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
Binary file added gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
6 changes: 6 additions & 0 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#Mon Nov 04 15:25:38 KST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Loading

0 comments on commit c4da086

Please sign in to comment.