Class: BroadcastHub::PayloadBuilder

Inherits:
Object
  • Object
show all
Defined in:
app/services/broadcast_hub/payload_builder.rb

Overview

Builds and validates normalized payloads sent through Action Cable.

Defined Under Namespace

Classes: ValidationError

Constant Summary collapse

VALID_ACTIONS =
%w[append prepend update remove].freeze
ACTIONS_REQUIRING_CONTENT =
%w[append prepend update].freeze
ALLOWED_KEYS =
%i[version action target content id meta].freeze

Class Method Summary collapse

Class Method Details

.build(action:, target:, content:, id:, meta: {}) ⇒ Hash

Builds the broadcast payload hash.

Parameters:

  • action (String)
  • target (String)

    DOM target identifier

  • content (String, nil)

    rendered HTML for non-remove actions

  • id (String)

    unique entry identifier

  • meta (Hash, nil) (defaults to: {})

    optional metadata included in the payload

Returns:

Raises:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/services/broadcast_hub/payload_builder.rb', line 23

def build(action:, target:, content:, id:, meta: {})
  validate_action!(action)
  validate_target!(target)
  validate_content!(action, content)

  payload = {
    version: BroadcastHub.configuration.payload_version,
    action: action,
    target: target,
    content: content,
    id: id,
    meta: normalize_meta(meta)
  }

  payload.slice(*ALLOWED_KEYS)
end