Is there a way to mount sub routers? context: Lets...
# javalin
a
Is there a way to mount sub routers? context: Lets say I want to make an OrderService and a UserService - both of them will return a router/route object or something and in main I want to mount them onto my main router - is that possible?
t
You can pass the Javalin instance into your service, there is no support for adding a group
Javalin encourages you to keep all your routes in the same file
a
How do i allow multiple devs to work on independent services and export a router to be mounted in that ‘one’ same file? You know? Like microservices but still in one app
Where each service returns routes to be mounted to the base
t
that sounds a bit contradictory 🤔
what is the reason for not wanting all the routes in one file if it is in fact one service ?
a
No - i am not saying it wont be in one file - i want them in one file I m asking - how can I organise it such that when you read that file the routes are grouped by services rather than this route goes to this handler - that route goes to this handler etc
Like a modular sub router design
t
i'm not sure if i understand, could you write pseudo code for what you want to achieve ?
a
https://www.devcon5.ch/en/blog/2017/09/15/vertx-modular-router-design/ This one is more geared towards vertx - but same thought Iterate over all services’ subrouters and mount them to a single global main router
t
it looks like they're just doing this:
Copy code
fun main() {

    val app = Javalin ... 
    
    val userService = UserService(deps)
    val smsService = SmsService(deps)
    
    userService.addRoutes(app)
    smsService.addRoutes(app)

}
since the
ApiBuilder
class in javalin uses a temporary static variable (which is only valid inside the scope of a
routes
call), you could potentially build your own fancy DSL for this (although i don't really recommend it)
a
Beautiful that’s what I was looking for - thanks!
So the javalin instance can be passed around np?
t
sure, it's just an object, pass it wherever you want
i've seen people use that pattern before
this tutorial does something similar: https://javalin.io/tutorials/javalin-java-10-google-guice
but i have never actually read the whole thing 😅
a
Is the pattern same if one service is exporting routes and one is exporting websocket handlers?
t
yes, they're both functions that basically add a lambda to a list of lambdas in the router
the signature for the websocket handler is
Copy code
fun handleWs(ws: WsHandler) {
    ws.onConnect...
    ws.onClose...
}
so you could make something like
Copy code
class MyService{
    fun addRoutes(app: Javalin) {
        app.get(path ::myGetHandler)
        <http://app.ws|app.ws>(path ::myWsHandler)
    }
}
a
Oh beautiful
Dude thank you so much 🙏
t
No problem