kotlin脚本
A while ago I needed to populate the Firestore database with some data from a Google Sheet document while developing a side project. I decided to give a try to Kotlin script. Choosing a Kotlin script is an easy step for an Android developer because of language familiarity and availability of Firebase Admin Java SDK.
不久前,我在开发副项目时需要用Google Sheet文档中的一些数据填充Firestore数据库。 我决定尝试一下Kotlin脚本。 由于对语言的了解和Firebase Admin Java SDK的可用性,对于Android开发人员而言,选择Kotlin脚本是一个简单的步骤。
脚本 (kscript)
To do this small task, we will need to add Firebase Admin Java SDK dependency. It would be also convenient to edit the script in IDE. We can do this easily with the help of kscript which provides the described and other important features.
为了完成此小任务,我们将需要添加Firebase Admin Java SDK依赖项。 在IDE中编辑脚本也很方便。 我们可以借助kscript轻松完成此任务,该脚本提供了已描述的功能和其他重要功能。
For example, with kscript, you can create a script file with .kts extension and declared dependencies inside and the tool will create a temporary IntelliJ project with needed Gradle dependencies for you. Details can be found in the appropriate section.
例如,使用kscript ,您可以创建一个扩展名为.kts并在内部声明依赖项的脚本文件,该工具将为您创建一个具有所需Gradle依赖项的临时IntelliJ项目。 可以在适当的部分找到详细信息。
设置Firebase (Setting up Firebase)
To start making calls to Firestore, we will need to create a service account in the project’s settings:
要开始调用Firestore,我们需要在项目的设置中创建一个服务帐户:
The next step is to generate a private key to give the script access to Firestore. The platform will let you download serviceAccountKey.json with needed credentials. Just place the file in the same directory with the script. Firestore initialization will look like this:
下一步是生成私钥,以使脚本可以访问Firestore。 该平台将允许您使用所需的凭据下载serviceAccountKey.json 。 只需将文件与脚本放在同一目录中即可。 Firestore初始化将如下所示:
#!/usr/bin/env kscript
@file:DependsOn("com.google.firebase:firebase-admin:6.13.0")
import com.google.auth.oauth2.GoogleCredentials
import com.google.cloud.firestore.Firestore
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.cloud.FirestoreClient
val DATABASE_URL = "https://your-database.firebaseio.com"
fun initFirestore(): Firestore {
val options = FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(FileInputStream("serviceAccountKey.json")))
.setDatabaseUrl(DATABASE_URL)
.build()
FirebaseApp.initializeApp(options)
return FirestoreClient.getFirestore()
}
传输资料 (Transferring data)
You can easily export a Google Sheet document as CSV by building a special download link. The URL should follow the next format:
通过构建特殊的下载链接,您可以轻松地将Google Sheet文档导出为CSV。 该网址应采用以下格式:
https://docs.google.com/spreadsheets/d/$documentId/gviz/tq?tqx=out:csv
https://docs.google.com/spreadsheets/d/ $ documentId / gviz / tq?tqx = out:csv
The documentId part can be retrieved from the document’s sharing URL:
可以从文档的共享URL检索documentId部分:
https://docs.google.com/spreadsheets/d/1y_TH7vLDxXtyPqFTmlWo04VEkRhHO0d-kB7-yXCzFbs/edit?usp=sharing
Don’t forget to enable access to everyone who has the link. It will let the script download the CSV.
不要忘记启用对具有链接的每个人的访问。 它将使脚本下载CSV。
在Kotlin中使用CSV (Working with CSV in Kotlin)
In order to parse a CSV document, you can write some sophisticated code that can manipulate rows and columns or you can just use opencsv. I decided to choose this library and focus on data validation instead. The best thing about Kotlin script is that you can write clean data structures while solving a task. For example, I declared a simple sealed class to represent two types of rows: valid and invalid.
为了解析CSV文档,您可以编写一些可以操纵行和列的复杂代码,也可以只使用opencsv 。 我决定选择此库,而专注于数据验证。 Kotlin脚本的最好之处在于,您可以在解决任务时编写干净的数据结构。 例如,我声明了一个简单的sealed class来表示两种类型的行:有效和无效。
将数据发送到Firestore (Sending data to Firestore)
The task is to rewrite the database atomically and Firebase Admin Java SDK supports needed calls. The interesting thing to note is that Firestore has two separate concepts: transactions and batched writes. If you don’t need to perform any read operation as a part of atomic operation then you can use batched writes. You can find the details in the official documentation.
任务是原子地重写数据库,并且Firebase Admin Java SDK支持所需的调用。 需要注意的有趣的是,Firestore有两个独立的概念:事务和批处理写入。 如果您不需要作为原子操作的一部分执行任何读取操作,则可以使用批量写入。 您可以在官方文档中找到详细信息。
脚本的实现 (The script’s implementation)
#!/usr/bin/env kscript
@file:DependsOn("com.google.firebase:firebase-admin:6.13.0")
@file:DependsOn("com.opencsv:opencsv:4.0")
import com.google.auth.oauth2.GoogleCredentials
import com.google.cloud.firestore.Firestore
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.cloud.FirestoreClient
import com.opencsv.CSVReader
import com.opencsv.CSVReaderBuilder
import java.io.FileInputStream
import java.io.Reader
import java.net.URL
val COLUMN_LANGUAGE_NAME = 0
val COLUMN_YEAR = 1
val DOCUMENT_URL =
"https://docs.google.com/spreadsheets/d/1y_TH7vLDxXtyPqFTmlWo04VEkRhHO0d-kB7-yXCzFbs/gviz/tq?tqx=out:csv"
val DATABASE_URL = "https://your-database.firebaseio.com"
println("1️⃣ Initializing Firestore…")
val db = initFirestore()
println("Firestore has been initialized")
println("\n2️⃣ Downloading the document into memory: $DOCUMENT_URL")
URL(DOCUMENT_URL)
.openStream()
.bufferedReader()
.csvReader()
.use { reader ->
val rows = reader.convertToDbRow()
println("Downloaded the document. There are ${rows.size} valid rows")
if (rows.isEmpty()) {
println("⚠️ There are no valid rows. The database won't be cleared")
return@use
}
println("\n3️⃣ Sending the data to Firestore…")
fillFirestore(rows)
}
println("Done \uD83D\uDC4D")
fun initFirestore(): Firestore {
val options = FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(FileInputStream("serviceAccountKey.json")))
.setDatabaseUrl(DATABASE_URL)
.build()
FirebaseApp.initializeApp(options)
return FirestoreClient.getFirestore()
}
fun Reader.csvReader(): CSVReader = CSVReaderBuilder(this)
.withSkipLines(1)
.build()
fun CSVReader.convertToDbRow(): List<Row.Valid> {
return this.readAll()
.map { parseRow(it) }
.filterIsInstance<Row.Valid>()
}
fun parseRow(row: Array<String>): Row {
return if (row.isRowValid()) {
val language = mapOf(
"name" to row.getOrNull(COLUMN_LANGUAGE_NAME)?.trim(),
"year" to row.getOrNull(COLUMN_YEAR)?.trim()
)
Row.Valid(language)
} else {
println("⚠️ Invalid row: ${row.contentToString()}")
Row.Invalid
}
}
fun Array<String>.isRowValid(): Boolean {
return when {
!this.hasValue(COLUMN_LANGUAGE_NAME) -> false
!this.hasValue(COLUMN_YEAR) -> false
else -> true
}
}
fun Array<String>.hasValue(index: Int): Boolean = getOrNull(index) != null
fun fillFirestore(rows: List<Row.Valid>) {
val languagesCollection = db.collection("languages")
val batch = db.batch()
languagesCollection.listDocuments().forEach { batch.delete(it) }
rows.forEach { batch.create(languagesCollection.document(), it.data) }
batch.commit().get()
}
sealed class Row {
class Valid(val data: Map<String, Any?>) : Row()
object Invalid : Row()
}
结论 (Conclusion)
Kotlin script in combination with kscript provides a good way of writing maintainable and reliable scripts. The learning curve is low for Android developers because of the familiar development environment. Just imagine that you can use coroutines, data classes, delegates properties, and other great features of Kotlin in your use cases.
Kotlin脚本与kscript结合使用提供了一种编写可维护且可靠的脚本的好方法。 由于熟悉的开发环境,Android开发人员的学习曲线很低。 试想一下,您可以在用例中使用协程 , 数据类 , 委托属性和Kotlin的其他出色功能。
链接 (Links)
翻译自: https://medium.com/@Holovin/filling-firestore-database-using-kotlin-script-e6c7743e1873
kotlin脚本



所有评论(0)