-
Notifications
You must be signed in to change notification settings - Fork 65
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Accept module plugs in Kino.Proxy.listen/1 (#448)
- Loading branch information
1 parent
cc87210
commit 4094617
Showing
1 changed file
with
37 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -72,14 +72,47 @@ defmodule Kino.Proxy do | |
> ``` | ||
""" | ||
|
||
@type plug() :: | ||
(Plug.Conn.t() -> Plug.Conn.t()) | ||
| module() | ||
| {module(), term()} | ||
|
||
@doc """ | ||
Registers a request listener. | ||
Expects the listener to be a function that handles a request | ||
`Plug.Conn`. | ||
Expects the listener to be a plug, that is, one of: | ||
* a function plug: a `fun(conn)` function that takes a `Plug.Conn` and returns a `Plug.Conn`. | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
wojtekmach
Author
Contributor
|
||
* a module plug: a `module` atom or a `{module, options}` tuple. | ||
""" | ||
@spec listen((Plug.Conn.t() -> Plug.Conn.t())) :: DynamicSupervisor.on_start_child() | ||
def listen(fun) when is_function(fun, 1) do | ||
@spec listen(plug()) :: DynamicSupervisor.on_start_child() | ||
def listen(plug) do | ||
fun = | ||
case plug do | ||
fun when is_function(fun, 1) -> | ||
fun | ||
|
||
mod when is_atom(mod) -> | ||
opts = mod.init([]) | ||
&mod.call(&1, opts) | ||
|
||
{mod, opts} when is_atom(mod) -> | ||
opts = mod.init(opts) | ||
&mod.call(&1, opts) | ||
|
||
other -> | ||
raise """ | ||
expected plug to be one of: | ||
* fun(conn) | ||
* module | ||
* {module, options} | ||
got: #{inspect(other)} | ||
""" | ||
end | ||
|
||
case Kino.Bridge.get_proxy_handler_child_spec(fun) do | ||
{:ok, child_spec} -> | ||
Kino.start_child(child_spec) | ||
|
Rigorously, this function does not follow the function plug contract since a function plug is a 2-arity function, right? 🤔
I don't think we need to change the docs, though. I think it's nice that the
Kino.Proxy.listen/1
can receive any shape of the plug, a function plug, or a module plug. With that contract, the user can leverage his knowledge about Plugs to understand that API.