Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Google Cloud Functions: try { Kotlin } insteadO...

Google Cloud Functions: try { Kotlin } insteadOf JavaScript

Slide for: Kotlin Night Milano 2018 (3° talk)

Video: https://www.youtube.com/watch?v=rN-7UeaxvFk

How to write (almost) free backend services on Google Cloud Functions in Kotlin

Avatar for Omar Miatello

Omar Miatello

March 15, 2018
Tweet

More Decks by Omar Miatello

Other Decks in Technology

Transcript

  1. Google Cloud Functions: try { Kotlin } insteadOf JavaScript How

    to write (almost) free backend services on Google Cloud Functions in Kotlin
  2. Omar Miatello Android Developer @ Organizer @ Personal profile google.com/+OmarMiatello

    Slides available on: Google Presentation https://goo.gl/CMVNqS Google Photo https://goo.gl/HpRLw4 Speaker Deck (by GitHub) https://speakerdeck.com/jacklt SlideShare (by LinkedIn) https://www.slideshare.net/OmarMiatello
  3. I’m an Android developer (since 2010) I use Kotlin (since

    2015) instead of Java I use a lot of Firebase services About me
  4. Target: cost-free backend! Free hosting options: • PHP (a lot

    of free hosting, since 2000) ◦ Altervista, Netsons, … • Solution PaaS (Platform as a Service) ◦ Google App Engine ▪ Support for: Node.js, Java, Ruby, C#, Go, Python e PHP, … ▪ 28 hours instance a day ◦ Amazon Web Services (Free tear only for the first 12 months) • Solution “serverless”
  5. Target: cost-free backend! Comparison free "serverless" plans: • Google Cloud

    Functions ◦ Node.js ◦ 2.000.000 free calls/month • Cloud Functions for Firebase ◦ Node.js ◦ 125.000 / 2.000.000 free calls/month • AWS Lambda ◦ Node.js, Java, C#, Go, Python ◦ 1.000.000 free calls/month
  6. 2.000.000 calls/month? What if: I call a function every second

    1 day = 86.400 seconds ~ 12 days = 1.000.000 seconds ~ 23 days = 2.000.000 seconds 30 days = 2.592.000 seconds
  7. 2.000.000 calls/month? How many users? 1 day = ~ 65.000

    calls depends on Average User Activity 100 calls/day = ~ 650 users/day 10 calls/day = ~ 6.500 users/day
  8. Setup: Cloud Functions + Kotlin (Node.js) + Kotlin for JavaScript

    picture: https://blog.jetbrains.com/kotlin/2017/11/kotlin-1-2-released
  9. Setup: Cloud Functions + Kotlin (Node.js) + Kotlin for JavaScript

    picture: https://blog.jetbrains.com/kotlin/2017/11/kotlin-1-2-released G etting started w ith K otlin for JavaScript
  10. New Project in Kotlin/JS • Download: IntelliJ IDEA Community Edition

    (Free) ◦ https://www.jetbrains.com/idea/download • New Project: Gradle > Kotlin (JavaScript) G etting started w ith K otlin for JavaScript
  11. New Project in Kotlin/JS • Download: IntelliJ IDEA Community Edition

    (Free) ◦ https://www.jetbrains.com/idea/download • New Project: Gradle > Kotlin (JavaScript) • GroupId: “com.example” & ArtifactId: “myservice” • Confirm default settings until “Finish” G etting started w ith K otlin for JavaScript
  12. Configure: Cloud Functions for Firebase • Create new project on

    Firebase (optional) ◦ Use console: https://console.firebase.google.com G etting started w ith K otlin for JavaScript
  13. Configure: Cloud Functions for Firebase • Create new project on

    Firebase (optional) ◦ Use console: https://console.firebase.google.com • Open Functions section > click “Start” G etting started w ith K otlin for JavaScript
  14. Configure: Cloud Functions for Firebase • Create new project on

    Firebase (optional) ◦ Use console: https://console.firebase.google.com • Open Functions section > click “Start” • Install Node.js: https://nodejs.org ◦ Command line: “npm install -g firebase-tools” and “npm install kotlin” ◦ Open Terminal in project folder and run “firebase init” (and follow instructions) G etting started w ith K otlin for JavaScript
  15. Configure: Gradle • Add these lines in build.gradle • Ready!

    ◦ Deploy command: firebase deploy compileKotlin2Js.kotlinOptions { moduleKind = "commonjs" outputFile = "functions/index.js" } G etting started w ith K otlin for JavaScript
  16. Kotlin for JavaScript JavaScript is a dynamically-typed language, which means

    it does not check types at compile-time. You can freely talk to JavaScript from Kotlin via dynamic types, but if you want the full power of Kotlin type system, you can create Kotlin headers for JavaScript libraries.
  17. Kotlin: useful keywords for JavaScript Keywords: • external - Modifier

    to tell Kotlin that a certain declaration is written in pure JavaScript. Compiler assumes that the implementation for the corresponding class, function or property is provided by the developer. • dynamic - The dynamic type basically turns off Kotlin's type checker. The most peculiar feature of dynamic is that we are allowed to call any property or function with any parameters on a dynamic variable.
  18. Kotlin: useful functions for JavaScript Extensions: • .asDynamic() - Reinterprets

    this value as a value of the dynamic type. • .unsafeCast<T>() - Reinterprets this “dynamic” value as a value of the specified type [T] (ex: String / Array) without any actual type checking. Methods: • js(code) - Puts the given piece of a JavaScript code right into the calling function. The compiler replaces call to `js(...)` code with the string constant provided as a parameter.
  19. Example: Utils.kt fun toJson(obj: dynamic) = JSON.stringify(obj) { key, value

    -> value ?: undefined } // Arrays / Map utils fun jsMap(init: (dynamic) -> Unit) = Any().apply { init(asDynamic()) }.asDynamic() fun keys(obj: dynamic) = js("Object").keys(obj).unsafeCast<Array<String>>() // JavaScript functions fun getDateOfWeek(week: Int, year: Int) = js(""" var simple = new Date(year, 0, 1 + (week - 1) * 7); var dow = simple.getDay(); var iso = simple; if (dow <= 4) iso.setDate(simple.getDate() - simple.getDay() + 1); else iso.setDate(simple.getDate() + 8 - simple.getDay()); return iso;""").unsafeCast<Date>()
  20. GET on /helloWorld external fun require(module: String): dynamic external val

    exports: dynamic fun main(args: Array<String>) { val fireFunctions = require("firebase-functions") val config = fireFunctions.config() exports.helloWorld = fireFunctions.https.onRequest { request, response -> console.log("Request headers: " + toJson(request.headers)) console.log("Request body: " + toJson(request.body)) response.send("Hello from Firebase!") } }
  21. Deploy Before deploy update Node.js dependencies, from command line use:

    • npm update • npm install Build index.js file from gradle and deploy on Firebase! • ./gradlew build • firebase deploy Demo: https://goo.gl/tkdvfk Full source: https://github.com/jacklt/firebase-cloud-functions-with-kotlin-js