policy_wonk v1.0.0-rc.0 PolicyWonk.Load View Source

This turns your resource module into a plug that can be used in a router.

Usage

The only time you should directly use the PolicyWonk.Load module is to call use PolicyWonk.Load when defining your resource module.

Example resource loader module:

  defmodule MyAppWeb.Resources do
    use PolicyWonk.Resource       # set up support for resources
    use PolicyWonk.Load           # turn this module into an resource loading into a plug

    def resource( _conn, :user, %{"id" => user_id} ) do
      case MyAppWeb.Account.get_user(user_id) do
        nil ->  {:error, :not_found}
        user -> {:ok, :user, user}
      end
    end

    def policy_error(conn, :not_found) do
      MyAppWeb.ErrorHandlers.resource_not_found(conn, "Resource Not Found")
    end
  end

To use your resources as a plug, you can just use the new module you created.

Load resources in a router:

  pipeline :browser_session do
    plug MyAppWeb.Resources,  :user
    plug MyAppWeb.Resources,  [:thing_a, :thing_b]
  end

You can also pass in a Keyword list with additional options

  plug MyAppWeb.Resources,  resources: [:user, :thing_a], async: true

If you use the keyword list of options, then the available options are

  • resources: a list of resources to load
  • async: a true/false flag indicating if the resources should be loaded asynchronously

async load default

When you add use PolicyWonk.Load to your resource module, the default is to set async loading to false. If you would like to set it as true, you can set as a use option.

  defmodule MyAppWeb.Resources do
    use PolicyWonk.Resource               # set up support for resources
    use PolicyWonk.Load, async: true      # turn this module into an resource loading into a plug