I try to develop firebase function with Kotlin in ...
# javascript
m
I try to develop firebase function with Kotlin in place of JS. In first place, I want to wrap expressjs (used by firebase to create endpoint). This is my code :
Copy code
val expressLib = require("express")

class Express(val app: dynamic = expressLib()) {

    fun get(route: String, callback: (req: Request, res: Response) -> Unit) {
        app.get(route, { req, res ->
            val request = Request(req)
            val response = Response(res)
            callback(request, response)
        });
    }

}

class Response(private val responseJs: dynamic) {

    fun send(data: String): Response {
        return Response(responseJs.send(data))
    }

    fun json(data: Any): Response {
        return Response(responseJs.send(data))
    }

}
Is it a good approach ?
a
I looks like you are trying create Kotlin API, which mimics an delegates to expressjs.
If that's the case you might want to consider using
external
declarations instead: https://kotlinlang.org/docs/reference/js-interop.html#external-modifier
That way you should be able to describe the expressjs API in a way Kotlin/JS compiler understands and use it with much less overhead.
If you do that, you'll need to use @JsModule annotation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-js-module/index.html
That way the compiler will know where to import the API from (i.e. will generate require('express') and whaterver you've declared from there)
m
Thank you, i'll try that!
a
Also there is a semi-automatic convertor from TypeScript definitions to Kotlin: https://github.com/Kotlin/ts2kt
I would recommend first writing a few external declarations by hand though
Otherwise you might get overwhelmed when looking at the generated code 😃
m
There is no TS file in express js framework... so... šŸ™‚
a
m
Cool ! I don't see it in the github repo, I didn't look further...
l
Hi, following up on the ts2kt converter
I’m struggling with where to put the generated code
do I put it in my src/kotlin folders ? seems ugly
or somewhere in the build/ folder ? but then, I don’t know where
a
How about creating a separate module "generated"?
l
I like it
except, those definitions have to be added because the ā€œmainā€ module requires them in its package.json
so putting it in a ā€œgeneratedā€ module could seem a little strange
but I have nothing better yet, thanks !
a
šŸ‘
m
It's very more easier :
Copy code
package express

@JsModule("express")

external class Express {

    fun get(route: String, callback: (req: dynamic, res: Response) -> dynamic)

    fun listen(port: Int, function: dynamic)

}

external  class Response {

    fun sendStatus(code: Int): Response

    fun type(type: String): Response

    fun send(data: String): Response

    fun json(data: Any): Response
}
thank you!
a
😃