Is there any way to call controller method from phoenix channel to and fro

1.1k Views Asked by At

I need to call a function inside the controller from phoenix channel. This is my phoenix channel

    //dashboardChannel.ex
    def join("dashboard:lobby", payload, socket) do
        IO.puts "Entered Room"

        if authorized?(payload) do
          {:ok, socket}
        else
          {:error, %{reason: "unauthorized"}}
        end
    end

This is my handle_in function

    //dashboardChannel.ex
    def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do

        broadcast_from! socket, "new_msg", %{uid: uid, body: body}
        MyApp.Endpoint.broadcast_from! self(), "dashboard:lobby", "new_msg", %{uid: uid, body: body}

        {:noreply, socket}
    end

The below is my controller function, The route for this controller will be "/users"

    //dashboardController.ex
    def index(conn, _params) do
        IO.puts "Enters Users Controller"
        MyApp.Endpoint.broadcast_from! self(), "dashboard:lobby", "new_msg", %{"uid" => "ac4452s", "body" => "Sample User"}
        IO.puts "Must have executed User Controller"

        users = Accounts.list_users() // It will list all my users
        render(conn, "index.json", users: users)
    end

I'am new to phoenix and elixir. I need to call the "/users" controller function from the phoenix channel above. How do i call call that. Is there any way to call a controller function from phoenix channel and also call the handle_in function which is "new_msg" from a controller method. Thanks in advance

The below is my requirement

  1. I need to call function of dashboardController's which is my "index"(route "/users") from dashboardChannel's handle_in function of new_msg in topic "dashboard:lobby"
  2. And also i need to call the handle_in function of dashboardChannel's new_msg in topic "dashboard:lobby" from dashboardController's index
0

There are 0 best solutions below