Skip to content

Latest commit

 

History

History
93 lines (70 loc) · 2.76 KB

part3.md

File metadata and controls

93 lines (70 loc) · 2.76 KB

Part 3 - Hello Kotlin

In this part you will setup basic KotlinJS project and rewrite functions from part 1 into Kotlin.

Steps:

  • Make sure that you have Kotlin JS installed (in functions sub-folder)
npm install --save kotlin
  • Open IntelliJ IDEA and create a new Kotlin project in the root folder. Use Kotlin(JavaScript) and Gradle in the wizard. As a result the folder functions should now be a subfolder of your Kotlin project.

  • Add the following block to build.gradle:

compileKotlin2Js.kotlinOptions {
    moduleKind = "commonjs"
    outputFile = "functions/build/index.js"
}
  • Create file src/main/kotlin/Index.kt and write the function testPush in basic KotlinJS:
external fun require(module: String): dynamic
external val exports: dynamic

val functions = require("firebase-functions")
val admin = require("firebase-admin")

data class Conversions(
    val eur: Float,
    val usd: Float? = null,
    val czk: Float? = null,
    val pln: Float? = null,
    val rub: Float? = null,
    val timestamp: Long? = null
)

fun main(args: Array<String>) {
    admin.initializeApp(functions.config().firebase)

    exports.testPush = functions.https.onRequest { req, res ->
        admin.database().ref("/conversions")
            .push(Conversions(req.query.eur.toString().toFloat()))
            .then { res.status(200).send("done") }
    }
}
  • Try to build and deploy your function:
./gradlew build
firebase deploy --only functions

It is possible that you get the error Error: Error parsing triggers: Cannot find module. If that is the case, run following commands to reset project dependencies:

cd functions
npm install --save kotlin
npm install --save firebase-admin
npm install --save firebase-functions

And try to build-deploy again.

  • Bonus: add a task to build and deploy with one command:
import org.apache.tools.ant.taskdefs.condition.Os
task deploy(type:Exec, dependsOn: 'build') {
    def firebaseExecutable = Os.isFamily(Os.FAMILY_WINDOWS) ? "firebase.cmd" : "firebase"
    commandLine firebaseExecutable, "deploy"
}
  • Deploy and verify your functions:
./gradlew deploy

Conclusions:

While you are using some Kotlin features like data classes, most of the code is of class dynamic, which is not a good thing. dynamic means that compiler is not going to even try to infer types and check anything so the resulting code is as error prone as basic JavaScript.

In next part we are going to fix this.

Links: