Class: Moleculer::Service::Action

Inherits:
Object
  • Object
show all
Includes:
Moleculer::Support
Defined in:
lib/moleculer/service/action.rb

Overview

Represents an action

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, service, method, options = {}) ⇒ Action

options will reflect the hash. provided type.

Parameters:

  • name (String|Symbol)

    the name of the action.

  • method (Symbol)

    the service method to be called.

  • service (Moleculer::Service::Base)

    the moleculer service class

  • options (Hash) (defaults to: {})

    action options.

Options Hash (options):

  • :cache (Boolean|Hash)

    if true, will use default caching options, if a hash is provided caching

  • params (Hash)

    list of param and param types. Can be used to coerce specific params to the



23
24
25
26
27
28
# File 'lib/moleculer/service/action.rb', line 23

def initialize(name, service, method, options = {})
  @name    = name
  @service = service
  @method  = method
  @options = options
end

Instance Attribute Details

#nameString (readonly)

Returns the name of the action.

Returns:

  • (String)

    the name of the action



12
13
14
# File 'lib/moleculer/service/action.rb', line 12

def name
  @name
end

#serviceObject (readonly)

Returns the value of attribute service.



12
13
14
# File 'lib/moleculer/service/action.rb', line 12

def service
  @service
end

Instance Method Details

#execute(context, broker) ⇒ Moleculer::Support::Hash

Returns a hash which will be converted into json for the response.

Parameters:

Returns:

  • (Moleculer::Support::Hash)

    returns a hash which will be converted into json for the response.

Raises:



35
36
37
38
39
40
41
42
43
# File 'lib/moleculer/service/action.rb', line 35

def execute(context, broker)
  response = @service.new(broker).public_send(@method, context)
  # rubocop disabled because in this case we need a specific error handling format
  raise Errors::InvalidActionResponse.new(response) unless response.is_a? Hash # rubocop:disable Style/RaiseArgs

  response
rescue StandardError => e
  broker.config.handle_error(e)
end

#nodeObject



45
46
47
# File 'lib/moleculer/service/action.rb', line 45

def node
  @service.node
end

#to_hObject



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/moleculer/service/action.rb', line 49

def to_h
  {
    name:    "#{@service.full_name}.#{name}",
    rawName: name,
    cache:   HashUtil.fetch(@options, :cache, false),
    metrics: {
      params: false,
      meta:   true,
    },
  }
end