anycable/anycable-client

Implement setParam for WebSocket transport

palkan opened this issue · 0 comments

Context

The setParam method in the Transport interface is meant to configure transport object parameters (key-value).

For example, we can specify an authentication token as a transport parameter: transport.setParam('token', 'secret'). The way a transport stores the parameters is implementation specific. For WebSockets, we suggest using query string params (i.e., /cable?token=secret).

Proposal

Implement setParam method for WebSocket transport, which should update the url by adding the provided params to a query string:

let ws = new WebSocketTransport('/cable')
ws.setParam('token', 'secret')
ws.url //=> `/cable?token=secret`

// when url contains params
let ws = new WebSocketTransport('/cable?foo=bar')
ws.setParam('token', 'secret')
ws.url //=> `/cable?foo=bar&token=secret`

ws.setParam('foo', 'baz')
ws.url //=> `/cable?foo=baz&token=secret`

Thoughts on implementation

We can use URL and searchParams under the hood (support in all major browsers and Node).

An example usage:

// transform existing URL string into an object
const uri = new URL(url)
// update search params
uri.searchParams.set(key, val)
// convert back to a string 
const newURL = `${uri.protocol}//${uri.host}${uri.pathname}?${uri.searchParams}`

NOTE: The example above assume an absolute URL; we should think about how to handle a relative one.