javalin / javalin-routing-extensions

Set of alternative routing implementations for Javalin 5.x
https://github.com/javalin/javalin-routing-extensions/wiki
MIT License
14 stars 2 forks source link

Websocket Annotation Support #45

Open Bastitron opened 2 months ago

Bastitron commented 2 months ago

Would be nice to have annotations for websocket handling. It would make sense to make them work just like the other annotations:

@Endpoints("/api")
static final class ExampleEndpoints {

    private final ExampleService exampleService;

    // pass dependencies required to handle requests
    public ExampleEndpoints(ExampleService exampleService) {
        this.exampleService = exampleService;
    }

    @WsConnect("/ws")
    void onConnect(Context ctx) {
        // ...
    }

    @WsError("/ws")
    void onError(Context ctx) {
        // ...
    }

    @WsClose("/ws")
    void onClose(Context ctx) {
        // ...
    }

    @WsMessage("/ws")
    void onMessage(Context ctx) {
        // ...
    }

    @WsBinaryMessage("/ws")
    void onBinaryMessage(Context ctx) {
        // ...
    }
}
dzikoysk commented 1 month ago

I think it makes sense to support WebSockets, but I also think it'd make more sense if we'd keep these listeners a bit more connected to each other. Maybe something like:

interface WebsocketHandler {
  fun onConnect(ctx: WsContext) {}
  fun onError(ctx: WsContext) {}
  fun onClose(ctx: WsContext) {}
  fun onMessage(ctx: WsContext) {}
}

// -- example impl:

@Endpoints("/api")
class ExampleEndpoints(val exampleService: ExampleService) {

    @Get("/get/{id}")
    fun findById(Context ctx) {
        // ...
    }

    @Ws("/connect")
    fun connect(): WebsocketHandler {
        return ExampleWs()
    }

    inner class ExampleWs : WebsocketHandler {
        private var internalState = "monke"

        override fun onConnect(ctx: WsContext) {
            this.internalState = exampleService.doSomething()
        }
    }
}
Bastitron commented 1 month ago

Good point, I would enjoy this kind of implementation.