[英]How to pass plug loaded data to LiveView components
Hi I'm using different domain names to load different data sets.您好我使用不同的域名来加载不同的数据集。 I'm currently using a custom plug to load the correct domain id based on the hostname.
我目前正在使用自定义插件根据主机名加载正确的域 ID。 Eg got this in my
endpoint.ex
just before the router:例如,在路由器之前的我的
endpoint.ex
中得到了这个:
plug WebApp.DomainCheck
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
...
plug WebApp.Router
And和
defmodule WebApp.DomainCheck do
import Plug.Conn
@behaviour Plug
def init([]), do: []
def call(conn, _options \\ []) do
domains = Model.load_allowed_domains()
case Map.get(domains, conn.host) do
nil ->
conn
|> resp(401, "Domain not allowed")
|> halt()
domain_id ->
conn
|> assign(:domain_id, domain_id)
end
end
end
Now this works for normal View
as I have the domain_id
assign in each of them.现在这适用于普通
View
,因为我在每个视图中都分配了domain_id
。 But how do I get the domain
data injected into my LiveView
s as well from a plug?但是我如何从插件中获取
domain
数据注入到我的LiveView
中呢?
Currently I've code duplicated the same domain check into every LiveViews mount() page:目前,我已将相同的域检查代码复制到每个 LiveViews mount()页面:
defmodule WebApp.WelcomeLive do
use WebApp, :live_view
@impl true
def mount(_args, _session, socket) do
domains = Model.load_allowed_domains()
host = socket.host_uri.host
case Map.get(domains, host) do
nil -> {:error, "Domain not allowed"}
domain_id -> {:ok, assign(socket, :domain_id, domain_id)}
end
end
Is there any way I can make a plug effective in pushing this data down to the live views without need to add code to each mount?有什么方法可以使插件有效地将这些数据推送到实时视图,而无需向每个安装添加代码?
I had a similar use case in my app where my plug puts the a user
struct on the assigns
and I wanted to keep that data inside live view without reloading all stuff.我在我的应用程序中有一个类似的用例,我的插件将
user
结构放在assigns
上,我想将该数据保留在实时视图中而不重新加载所有内容。
The only way I could achieve that was using the option session
from the live
route passing it a MFA.我可以实现的唯一方法是使用选项
session
从通过 MFA 的live
路由。
In the router you will have something like在路由器中,您将拥有类似的东西
live "/page", WebApp.SomeLiveView, :show, session: {WebAppp.Helpers, :keep_domain_id, []}
and your WebApp.Helpers
will have that function returning what you want to be passed to your live view as session
.并且您的
WebApp.Helpers
将拥有 function 将您想要传递给实时视图的内容返回为session
。
defmodule WebApp.Helpers do
def keep_domain_id(conn) do
%{"domain_id" => conn.assigns.domain_id}
end
end
Then in your mount
on you will have "domain_id"
key in your session
然后在您的
mount
中,您的session
中将有"domain_id"
键
defmodule WebApp.WelcomeLive do
use WebApp, :live_view
@impl true
def mount(_args, %{"domain_id" => domain} = _session, socket) do
...
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.