// NOTE: The contents of this file will only be executed if // you uncomment its entry in "assets/js/app.js". // Bring in the socket library import {Socket} from "phoenix" // And connect to the path in "lib/river_connect_web/endpoint.ex". We pass the // token for authentication. Read below how it should be used. let params = {user_id: window.userId || "guest-" + Math.floor(Math.random() * 1000)} let socket = new Socket("/socket", {params: params}) // When you connect, you'll often need to authenticate the client. // For example, imagine you have an authentication plug, `MyAuth`, // which authenticates the session and assigns a `:current_user`. // If the current user exists you can set a own_id in the window // object in root.html.heex: // // // // Now you need to pass this token to JavaScript. You can do so // inside the socket implementation in "lib/river_connect_web/channels/user_socket.ex": // // def connect(%{"token" => token}, socket, _connect_info) do // # max_age: 1209600 is equivalent to two weeks in seconds // case Phoenix.Token.verify(socket, "user socket", token, max_age: 1_209_600) do // {:ok, user_id} -> // {:ok, assign(socket, :user, user_id)} // {:error, reason} -> // :error // end // end // // Finally, connect to the socket: socket.connect() // Now that you are connected, you can join channels with a topic. // Let's assume you have a channel with a topic named `room` and the // subtopic is its id - in this case 42: // // let channel = socket.channel("room:42", {}) // channel.join() // .receive("ok", resp => { console.log("Joined successfully", resp) }) // .receive("error", resp => { console.log("Unable to join", resp) }) // // export default socket to import it in other files export default socket