ktorio / ktor

Framework for quickly creating connected applications in Kotlin with minimal effort
https://ktor.io
Apache License 2.0
13.03k stars 1.07k forks source link

How to consume an authenticated WebSocket using a JS client? #1016

Closed lamba92 closed 5 years ago

lamba92 commented 5 years ago

I need to send the log of the server through a WebSocket and it works just fine. Now I want use an authenticated route but I cannot find a client that has Auth built in.

If I am not mistaken the Ktor JS client does not allow WebSockets. Is the CIO engine available for JS? If so we're I could find some documentation oh how to use it? Of course would need to add it to my project, which happens to be an Angular7 SPA. How do I output all the stuff including the Kotlin stdlib-js?

e5l commented 5 years ago

Hi @lamba92, ktor-client-js implements websockets in 1.2.0-alpha-1

lamba92 commented 5 years ago

Wold it be possible to use it directly into TypeScript? If not, could you provide some advice on how to output something usable inside an Angular project? I have very little experience with JS in general and Kotlin/JS as well.

EDIT: I was correctly able to create a Gradle project.

lamba92 commented 5 years ago

Well I think I managed to wrap (in)decently the Ktor client so that it's almost transparently usable from JS. Now how do correctly import what is outputted from this build into any JS project?

anton-bannykh commented 5 years ago

@lamba92 Kotlin/JS exports every public declaration as your.package.name.Declaration. That means that from a javascript project you should be able consume the resulting <your-module-name>.js file regularly (e.g. var foo = require('some/path/<your-module-name>.js') and then use it like so: new foo.your.package.name.Declaration("Hi1")

Keep in mind that you need to choose the correct module kind when compiling your module to JS, otherwise your environment won't be able to load it: https://kotlinlang.org/docs/tutorials/javascript/working-with-modules/working-with-modules.html

When in doubt I suggest umd, as it covers most use-cases.

e5l commented 5 years ago

Hi @lamba92, do you have any questions remaining?

e5l commented 5 years ago

Closed. Feel free to reopen if the issue is active.

lamba92 commented 5 years ago

Turns out the plain JS WebSocket class can handle it very well. Thanks to this answer on StackOverflow I was able to set the header without any external library. Still lame the fact that Angular HttpClient does not support websockets out of the box.