LoginSignup
3
0

More than 5 years have passed since last update.

Phoenixを触ってみる その4

Posted at

その3に引き続き
https://hexdocs.pm/phoenix/routing.html#pipelines
のページから

Pipelines

パイプラインは各リクエストに適用できる共通処理のようなものと思って良さそう。
以下特徴を持つ

  • リクエストに対して何かしらの処理や変換を行う
  • 順序を決められる

一つ一つの処理はPlugが担っていて、それを順序に沿って並べたものがpipeline。
※Plugって何よ、というのはまたいつか

今までのサンプルでも、こんな感じで定義されている。

router.ex
pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
end

pipeline :api do
  plug :accepts, ["json"]
end

pipelineを適用するには、pipe_throughを使う。

router.ex
scope "/", HelloWeb do
  pipe_through :browser
  get "/hello", HelloController, :index
end

この場合、:browserパイプラインはHelloControllerのindexが呼ばれる前に適用される。
コントローラに前処理を追加できるということらしい。

また、パイプラインを複数適用したり、パスによって適用するパイプラインを分けることも可能

rpouter.ex
scope "/admin", as: :admin do
  pipe_through [:browser, :admin_check] # /adminのときだけpipelineを追加
  ()
end

scope "/", HelloWeb do
  pipe_through :browser # こっちには :admin_checkは適用しない
  ()
end

ChannelRoutes

いきなりWebSocketの話。
WebSocketの場合はRouteの書き方が変わってきますよ、という話。
というかもはやRoutesではなく、endpointに直接書く。

endpoint.ex
socket "/socket", HelloWeb.UserSocket

mix phx.newの段階でこのサンプル記述は入っているはず。
Socket周りの実装は別の章であるようなので、ここでは割愛。

とりあえずrouterではないよ、ってことだけ頭に入れておけば良さげ。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0