unfetched.ex (1284B)
1 defmodule Plug.Conn.Unfetched do 2 @moduledoc """ 3 A struct used as default on unfetched fields. 4 5 The `:aspect` key of the struct specifies what field is still unfetched. 6 7 ## Examples 8 9 unfetched = %Plug.Conn.Unfetched{aspect: :cookies} 10 11 """ 12 13 defstruct [:aspect] 14 @type t :: %__MODULE__{aspect: atom()} 15 16 @behaviour Access 17 18 def fetch(%{aspect: aspect}, key) do 19 raise_unfetched(__ENV__.function, aspect, key) 20 end 21 22 def get(%{aspect: aspect}, key, _value) do 23 raise_unfetched(__ENV__.function, aspect, key) 24 end 25 26 def get_and_update(%{aspect: aspect}, key, _fun) do 27 raise_unfetched(__ENV__.function, aspect, key) 28 end 29 30 def pop(%{aspect: aspect}, key) do 31 raise_unfetched(__ENV__.function, aspect, key) 32 end 33 34 defp raise_unfetched({access, _}, aspect, key) do 35 raise ArgumentError, 36 "cannot #{access} key #{inspect(key)} from conn.#{aspect} " <> 37 "because they were not fetched" <> hint(aspect) 38 end 39 40 defp hint(aspect) when aspect in [:cookies, :query_params], 41 do: ". Call Plug.Conn.fetch_#{aspect}/2, either as a plug or directly, to fetch it" 42 43 defp hint(aspect) when aspect in [:params, :body_params], 44 do: ". Configure and invoke Plug.Parsers to set params based on the request" 45 46 defp hint(_), do: "" 47 end