Initial commit: there's still tons of base Phoenix boilerplate to remove, but the...
[tech-radar-editor.git] / web / static / js / socket.js
1 // NOTE: The contents of this file will only be executed if
2 // you uncomment its entry in "web/static/js/app.js".
3
4 // To use Phoenix channels, the first step is to import Socket
5 // and connect at the socket path in "lib/my_app/endpoint.ex":
6 import {Socket} from "phoenix"
7
8 let socket = new Socket("/socket", {params: {token: window.userToken}})
9
10 // When you connect, you'll often need to authenticate the client.
11 // For example, imagine you have an authentication plug, `MyAuth`,
12 // which authenticates the session and assigns a `:current_user`.
13 // If the current user exists you can assign the user's token in
14 // the connection for use in the layout.
15 //
16 // In your "web/router.ex":
17 //
18 // pipeline :browser do
19 // ...
20 // plug MyAuth
21 // plug :put_user_token
22 // end
23 //
24 // defp put_user_token(conn, _) do
25 // if current_user = conn.assigns[:current_user] do
26 // token = Phoenix.Token.sign(conn, "user socket", current_user.id)
27 // assign(conn, :user_token, token)
28 // else
29 // conn
30 // end
31 // end
32 //
33 // Now you need to pass this token to JavaScript. You can do so
34 // inside a script tag in "web/templates/layout/app.html.eex":
35 //
36 // <script>window.userToken = "<%= assigns[:user_token] %>";</script>
37 //
38 // You will need to verify the user token in the "connect/2" function
39 // in "web/channels/user_socket.ex":
40 //
41 // def connect(%{"token" => token}, socket) do
42 // # max_age: 1209600 is equivalent to two weeks in seconds
43 // case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
44 // {:ok, user_id} ->
45 // {:ok, assign(socket, :user, user_id)}
46 // {:error, reason} ->
47 // :error
48 // end
49 // end
50 //
51 // Finally, pass the token on connect as below. Or remove it
52 // from connect if you don't care about authentication.
53
54 socket.connect()
55
56 // Now that you are connected, you can join channels with a topic:
57 let channel = socket.channel("topic:subtopic", {})
58 channel.join()
59 .receive("ok", resp => { console.log("Joined successfully", resp) })
60 .receive("error", resp => { console.log("Unable to join", resp) })
61
62 export default socket