Hi all,
I’m using the Phoenix npm package (the js client).
How to reconnect the socket with new parameters?
- socket.conn.close() ?
- disconnect() -> connect() ?
As far as I see, there is no “reconnect()” function (public API):
https://hexdocs.pm/phoenix/js/index.html#socket
Something like this?
let reconnectTimer = new Timer(() => this.connect(), function(tries){
return [1000, 5000, 10000][tries - 1] || 10000
})
reconnectTimer.scheduleTimeout() // fires after 1000
reconnectTimer.scheduleTimeout() // fires after 5000
reconnectTimer.reset()
reconnectTimer.scheduleTimeout() // fires after 1000
Code from the documentation.
I need manual reconnection (auth token updates).
What do you mean by this?
You have the connect() function that can be used for this or am i missing something?
Please offer an example.
Hi,
import * as AbsintheSocket from '@absinthe/socket';
import {createAbsintheSocketLink} from '@absinthe/socket-apollo-link';
import {Socket as PhoenixSocket} from 'phoenix';
export const WEBSOCKET_SERVER_URI = 'ws://localhost:4000/socket';
const ACCESS_TOKEN_PARAM = 'token';
export const phoenixSocket = new PhoenixSocket(
WEBSOCKET_SERVER_URI,
{
params: () => {
return {token: window.localStorage.getItem(ACCESS_TOKEN_PARAM)};
},
}
);
export default createAbsintheSocketLink(AbsintheSocket.create(phoenixSocket));
- login(user): (HTTP Request).
- token != null -> update socket params -> phoenixSocket.reconnect()
- logout(user): (HTTP Request).
- token == null -> update socket params -> phoenixSocket.reconnect()
- refresh(token):
- old_token != new_token -> update_socket_params -> phoenixSocket.reconnect()
After some searching found this:
Code from Phoenix.js reconnect params
socket.onOpen(() => { socket.params = () => ({ reconnect: true, … }) })
I think this piece can be used with some if statements for each case you mentioned.
So
if (token!=null){
socket.onOpen(() => {
socket.params = () => ({ reconnect: true, … })
})
}
I think this should work, this is from the top of my head.
The client reconnection is not documented.
With this option you can reconnect to backend:
socket.conn.close()
I am glad you found the solution, after that run through the docs.