Nebulex v1.2.2 Nebulex.Hook behaviour View Source

This module specifies the behaviour for pre/post hooks callbacks. These functions are defined in order to intercept any cache operation and be able to execute a set of actions before and/or after the operation takes place.

Execution modes

It is possible to setup the mode how the hooks are evaluated. The pre_hooks/0 and post_hooks/0 callbacks must return a tuple {mode, hook_funs}, where the first element mode is the one that defines the execution mode. The available modes are:

  • :async - (the default) all hooks are evaluated asynchronously (in parallel) and their results are ignored.

  • :sync - hooks are evaluated synchronously (sequentially) and their results are ignored.

  • :pipe - similar to :sync but each hook result is passed to the next one and so on, until the last hook evaluation is returned.

Example

defmodule MyApp.MyCache do
  use Nebulex.Cache,
    otp_app: :my_app,
    adapter: Nebulex.Adapters.Local

  def pre_hooks do
    {:async, [... your pre hook functions ...]}
  end

  def post_hooks do
    {:pipe, [... your post hook functions ...]}
  end
end

Link to this section Summary

Types

Defines a cache command

Defines the hook callback function

Hook execution mode

Functions

Evaluates the hooks according to the given execution mode.

Callbacks

Returns a list of hook functions that will be executed after invoke the cache action.

Returns a list of hook functions that will be executed before invoke the cache action.

Link to this section Types

Specs

command() :: {Nebulex.Cache.t(), action :: atom(), args :: [any()]}

Defines a cache command

Specs

hook_fun() :: (result :: any(), command() -> any())

Defines the hook callback function

Specs

mode() :: :async | :sync | :pipe

Hook execution mode

Link to this section Functions

Link to this function

eval(arg, command, result)

View Source

Specs

eval({mode(), hooks :: [hook_fun()]}, command(), result :: any()) :: any()

Evaluates the hooks according to the given execution mode.

Link to this section Callbacks

Specs

post_hooks() :: {mode(), [hook_fun()]}

Returns a list of hook functions that will be executed after invoke the cache action.

Examples

defmodule MyCache do
  use Nebulex.Cache,
    otp_app: :my_app,
    adapter: Nebulex.Adapters.Local

  def post_hooks do
    {:pipe, [&post_hook/2]}
  end

  def post_hook(result, {_, :set, _} = call) do
    send(:hooked_cache, call)
  end

  def post_hook(_, _) do
    :noop
  end
end

Specs

pre_hooks() :: {mode(), [hook_fun()]}

Returns a list of hook functions that will be executed before invoke the cache action.

Examples

defmodule MyCache do
  use Nebulex.Cache,
    otp_app: :my_app,
    adapter: Nebulex.Adapters.Local

  def pre_hooks do
    pre_hook =
      fn
        (result, {_, :get, _} = call) ->
          # do your stuff ...
        (result, _) ->
          result
      end

    {:async, [pre_hook]}
  end
end