Lavash.Optimistic.ActionMacro (Lavash v0.4.0-rc.3)

Copy Markdown View Source

Macro for defining optimistic actions that run on both client and server.

This macro captures the source code of the run and validate functions for JavaScript compilation, then stores the action in a module attribute.

Separated from Lavash.Optimistic.Macros to avoid conflicts with Spark DSL's calculate entity.

Summary

Functions

Defines an optimistic action that runs on both server and client.

Functions

optimistic_action(name, field, opts)

(macro)

Defines an optimistic action that runs on both server and client.

This macro captures the source code of the run and validate functions for JavaScript compilation, then stores the action in a module attribute.

Options

  • :run - Required. Function fn current, value -> new_value end that transforms the field.
         For key-based actions, receives `fn item, value -> updated_item | :remove end`.
         Shorthands: `:remove` for removal actions, `:set` to directly set the value.
  • :validate - Optional. Function fn current, value -> boolean end for validation
  • :key - Optional. For array-of-objects: the field used to identify items (e.g., :id).
         When specified, the run function operates on the matched item instead of the array.
  • :max - Optional. Field name containing max length for array fields

Example

# Simple array of scalars
optimistic_action :add, :tags,
  run: fn tags, tag -> tags ++ [tag] end,
  validate: fn tags, tag -> tag not in tags end,
  max: :max_tags

optimistic_action :remove, :tags,
  run: fn tags, tag -> Enum.reject(tags, &(&1 == tag)) end

# Array of objects with key-based identification
optimistic_action :update_quantity, :items,
  key: :id,
  run: fn item, delta -> %{item | quantity: item.quantity + delta} end

optimistic_action :remove_item, :items,
  key: :id,
  run: :remove  # Shorthand for removal