commands

package
v1.1.4-10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2022 License: MIT Imports: 5 Imported by: 14

Documentation

Overview

Contains implementation of Command design patterns, which can be used to implement various remote procedure calls (RPCs). RPCs replace unique calls with universal "message transfer" calls, in which the message itself contains the called method's signature, as well as the parameters to pass for execution.

When designing calls of methods/commands using the Command design pattern, uniform interfaces can be used, which, in turn, allow any amount of concrete methods to be called.

Command design patterns can be used for intercepting messages and for various logging implementations.

These design patterns allow us to create Commandable Interfaces, which are completely universal. If an object extends ICommandable and returns a CommandSet, then we can implement, with minimal code, a commandable client for this object, using various technologies.

Commandable Interfaces – part of the command design pattern, used to make classes with certain logic, which are capable of receiving and processing commands in this universal form.

Command interceptors – modify the message execution pipeline. Command interceptors are used to intercept calls, perform a set of actions, and, optionally, cancel the command's actual execution by simply returning a result. This logic is used in aspect-oriented programming. Aspect-oriented programming contains perpendicular logic (aspects, for example: logging, caching, blocking), which can be removed from the business logic and added to these perpendicular calls. When using interceptors, a command can pass through an execution chain, consisting of interceptors, which can:

simply make some note of the command, notify, log, get metrics, or do some other passive task; or intercept the command completely and, for example, return a previous record of the call from the cache. A command’s return value can also be intercepted in a similar manner: the result can be written to cache, so that the next call doesn’t have to be made. Intercepted commands are used as pattern decorators in the command design pattern. They are represented as regular commands, but run their own logic before calling the actual command.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Command

type Command struct {
	// contains filtered or unexported fields
}

Concrete implementation of ICommand interface. Command allows to call a method or function using Command pattern. Example:

command := NewCommand("add", null, func (correlationId string, args *run.Parameters)(interface{}, err) {
	param1 := args.getAsFloat("param1");
    param2 := args.getAsFloat("param2");
    return (param1 + param2), nil;
});

result, err := command.Execute("123", Parameters.NewParametersFromTuples("param1", 2, "param2", 2))
if (err) {
	fmt.Println(err)
} else {
	fmt.Println("2 + 2 = " + result)
}
// Console output: 2 + 2 = 4

func NewCommand

func NewCommand(name string, schema validate.ISchema,
	action func(correlationId string, args *run.Parameters) (interface{}, error)) *Command

Creates a new command object and assigns it's parameters.

Parameters

  • name: string - the command name.

  • schema: validate.ISchema the schema to validate command arguments.

  • action: func(correlationId string, args *run.Parameters) (interface{}, error) the function to be executed by this command.

    Returns *Command

func (*Command) Execute

func (c *Command) Execute(correlationId string, args *run.Parameters) (interface{}, error)

Executes the command. Before execution it validates args using the defined schema. The command execution intercepts exceptions raised by the called function and returns them as an error in callback. Parameters:

correlationId: string - (optional) transaction id to trace execution through call chain.
args: run.Parameters - the parameters (arguments) to pass to this command for execution.

Returns (interface{}, error)

func (*Command) GetSchema added in v1.0.3

func (c *Command) GetSchema() validate.ISchema

GetSchema methods return validation schema for this command

func (*Command) Name

func (c *Command) Name() string

Gets the command name.

Returns string - the name of this command.

func (*Command) Validate

func (c *Command) Validate(args *run.Parameters) []*validate.ValidationResult

Validates the command args before execution using the defined schema.

Parameters:

args: run.Parameters - the parameters (arguments) to validate using this command's schema.

Returns []*validate.ValidationResult an array of ValidationResults or an empty array (if no schema is set).

type CommandSet

type CommandSet struct {
	// contains filtered or unexported fields
}

Contains a set of commands and events supported by a commandable object. The CommandSet supports command interceptors to extend and the command call chain.

CommandSets can be used as alternative commandable interface to a business object. It can be used to auto generate multiple external services for the business object without writing much code. see Command see Event see ICommandable

Example:

 type MyDataCommandSet {
	CommandSet
    _controller IMyDataController
 }
    func (dcs * MyDataCommandSet) CreateMyDataCommandSet(controller IMyDataController) { // Any data controller interface
        dcs._controller = controller
        dcs.addCommand(dcs.makeGetMyDataCommand())
    }

    func (dcs * MyDataCommandSet) makeGetMyDataCommand() ICommand {
        return NewCommand(
          'get_mydata',
          null,
          (correlationId: string, args: Parameters, func (correlationId string, args *run.Parameters)(interface{}, err) {
              let param = args.getAsString('param');
              return dcs._controller.getMyData(correlationId, param,);
          }
        );
    }

func NewCommandSet

func NewCommandSet() *CommandSet

Creates an empty CommandSet object. Returns *CommandSet

func (*CommandSet) AddCommand

func (c *CommandSet) AddCommand(command ICommand)

Adds a command to this command set. see ICommand Parameters:

  • command: ICommand the command to add.

func (*CommandSet) AddCommandSet

func (c *CommandSet) AddCommandSet(commandSet *CommandSet)

Adds all of the commands and events from specified command set into this one. Parameters:

  • commandSet: *CommandSet the CommandSet to add.

func (*CommandSet) AddCommands

func (c *CommandSet) AddCommands(commands []ICommand)

Adds multiple commands to this command set. see ICommand Parameters:

  • commands: []ICommand the array of commands to add.

func (*CommandSet) AddEvent

func (c *CommandSet) AddEvent(event IEvent)

Adds an event to this command set. see IEvent Parameters:

  • event: IEvent the event to add.

func (*CommandSet) AddEvents

func (c *CommandSet) AddEvents(events []IEvent)

Adds multiple events to this command set. see IEvent Parameters:

  • events: []IEvent the array of events to add.

func (*CommandSet) AddInterceptor

func (c *CommandSet) AddInterceptor(interceptor ICommandInterceptor)

Adds a command interceptor to this command set. see ICommandInterceptor Parameters:

-interceptor: ICommandInterceptor
the interceptor to add.

func (*CommandSet) AddListener

func (c *CommandSet) AddListener(listener IEventListener)

Adds a listener to receive notifications on fired events. see IEventListener Parameters:

  • listener: IEventListener the listener to add.

func (*CommandSet) Commands

func (c *CommandSet) Commands() []ICommand

Gets all commands registered in this command set. see ICommand Returns []ICommand a list of commands.

func (*CommandSet) Events

func (c *CommandSet) Events() []IEvent

Gets all events registred in this command set. see IEvent Returns []IEvent a list of events.

func (*CommandSet) Execute

func (c *CommandSet) Execute(correlationId string, commandName string, args *run.Parameters) (result interface{}, err error)

func (*CommandSet) FindCommand

func (c *CommandSet) FindCommand(commandName string) ICommand

Searches for a command by its name. see ICommand Parameters:

  • commandName: string the name of the command to search for.

Returns ICommand the command, whose name matches the provided name.

func (*CommandSet) FindEvent

func (c *CommandSet) FindEvent(eventName string) IEvent

Searches for an event by its name in this command set. see IEvent Parameters:

  • eventName: string the name of the event to search for.

Returns IEvent the event, whose name matches the provided name.

func (*CommandSet) Notify

func (c *CommandSet) Notify(correlationId string, eventName string, args *run.Parameters)

Fires event specified by its name and notifies all registered listeners Parameters:

  • correlationId: string (optional) transaction id to trace execution through call chain.
  • eventName: string the name of the event that is to be fired.
  • args: Parameters the event arguments (parameters).

func (*CommandSet) RemoveListener

func (c *CommandSet) RemoveListener(listener IEventListener)

Removes previosly added listener. see IEventListener Parameters:

  • listener: IEventListener the listener to remove.

func (*CommandSet) Validate

func (c *CommandSet) Validate(commandName string, args *run.Parameters) []*validate.ValidationResult

Validates args for command specified by its name using defined schema. If validation schema is not defined than the methods returns no errors. It returns validation error if the command is not found. see Command see Parameters see ValidationResult Parameters:

  • commandName: string the name of the command for which the 'args' must be validated.
  • args: Parameters the parameters (arguments) to validate.

Returns []ValidationResult an array of ValidationResults. If no command is found by the given name, then the returned array of ValidationResults will contain a single entry, whose type will be ValidationResultType.Error.

type Event

type Event struct {
	// contains filtered or unexported fields
}

Concrete implementation of IEvent interface. It allows to send asynchronous notifications to multiple subscribed listeners. Example:

event: = NewEvent("my_event");

event.AddListener(myListener);

event.Notify("123", Parameters.fromTuples(
  "param1", "ABC",
  "param2", 123
));

func NewEvent

func NewEvent(name string) *Event

func (*Event) AddListener

func (c *Event) AddListener(listener IEventListener)

func (*Event) Listeners

func (c *Event) Listeners() []IEventListener

func (*Event) Name

func (c *Event) Name() string

func (*Event) Notify

func (c *Event) Notify(correlationId string, args *run.Parameters)

func (*Event) RemoveListener

func (c *Event) RemoveListener(listener IEventListener)

type ICommand

type ICommand interface {
	run.IExecutable
	// Gets the command name.
	// Returns string
	// the command name.
	Name() string
	// Validates command arguments before execution using defined schema.
	// see
	// Parameters
	// see
	// ValidationResult
	// Parameters:
	//  - args: Parameters
	//  the parameters (arguments) to validate.
	// Returns ValidationResult[]
	// an array of ValidationResults.
	Validate(args *run.Parameters) []*validate.ValidationResult
}

type ICommandInterceptor

type ICommandInterceptor interface {
	// Gets the name of the wrapped command.
	// The interceptor can use this method to override the command name.
	// Otherwise it shall just delegate the call to the wrapped command.
	// Parameters:
	//  - command: ICommand
	//  the next command in the call chain.
	// Returns string
	// the name of the wrapped command.
	Name(command ICommand) string

	// 	Executes the wrapped command with specified arguments.
	// The interceptor can use this method to intercept and alter the command execution.
	// Otherwise it shall just delete the call to the wrapped command.
	// see
	// Parameters
	// Parameters:
	//  - correlationId: string
	//  (optional) transaction id to trace execution through call chain.
	//  - command: ICommand
	//  the next command in the call chain that is to be executed.
	//  - args: Parameters
	// the function that is to be called once execution is complete.
	// If an exception is raised, then it will be called with the error.
	// Returns:
	// result: interface{}
	// err: error
	Execute(correlationId string, command ICommand, args *run.Parameters) (interface{}, error)

	// Validates arguments of the wrapped command before its execution.
	// The interceptor can use this method to intercept and alter validation of the command arguments.
	// Otherwise it shall just delegate the call to the wrapped command.
	// see
	// Parameters
	// see
	// ValidationResult
	// Parameters:
	//  - command: ICommand
	//  the next command in the call chain to be validated against.
	//  - args: Parameters
	//  the parameters (arguments) to validate.
	// Returns []*ValidationResult
	// an array of *ValidationResults.
	Validate(command ICommand, args *run.Parameters) []*validate.ValidationResult
}

An interface for stackable command intercepters, which can extend and modify the command call chain. This mechanism can be used for authentication, logging, and other functions. see ICommand see InterceptedCommand

type ICommandable

type ICommandable interface {
	// 	Gets a command set with all supported commands and events.
	// see
	// CommandSet
	// Returns *CommandSet
	// a command set with commands and events.
	GetCommandSet() *CommandSet
}

type IEvent

type IEvent interface {
	run.INotifiable

	// Gets the event name.
	// Returns string
	// the name of the event.
	Name() string

	// Gets all subscribed listeners.
	// Returns []IEventListener
	// a list of listeners.
	Listeners() []IEventListener

	// Adds a listener to receive notifications for this event.
	// Parameters:
	//  - listener: IEventListener
	//  the listener reference to add.
	AddListener(listener IEventListener)

	// Removes a listener, so that it no longer receives notifications for this event.
	// Parameters
	//  - listener: IEventListener
	//  the listener reference to remove.
	RemoveListener(listener IEventListener)
}

type IEventListener

type IEventListener interface {
	// A method called when events this listener is subscrubed to are fired.
	// Parameters:
	//  - correlationId: string
	//  (optional) transaction id to trace execution through call chain.
	//  - e: IEvent
	//  a fired evemt
	//  - value: *run.Parameters
	//  event arguments.
	OnEvent(correlationId string, e IEvent, value *run.Parameters)
}

type InterceptedCommand

type InterceptedCommand struct {
	// contains filtered or unexported fields
}

Implements a command wrapped by an interceptor. It allows to build command call chains. The interceptor can alter execution and delegate calls to a next command, which can be intercepted or concrete. see ICommand see ICommandInterceptor

Example:

type CommandLogger {
	msg string
}

func (cl * CommandLogger) Name(command ICommand) string {
    return command.Name();
}

func (cl * CommandLogger) Execute(correlationId string, command ICommand, args Parameters) (res interface{}, err error){
    fmt.Println("Executed command " + command.Name());
    return command.Execute(correlationId, args);
}

func (cl * CommandLogger) Validate(command: ICommand, args: Parameters): ValidationResult[] {
    return command.Validate(args);
}

logger := CommandLogger{mgs:"CommandLoger"};
loggedCommand = NewInterceptedCommand(logger, command);

// Each called command will output: Executed command <command name>

func NewInterceptedCommand

func NewInterceptedCommand(interceptor ICommandInterceptor, next ICommand) *InterceptedCommand

Creates a new InterceptedCommand, which serves as a link in an execution chain. Contains information about the interceptor that is being used and the next command in the chain. Parameters:

  • interceptor: ICommandInterceptor the interceptor that is intercepting the command.
  • next: ICommand (link to) the next command in the command's execution chain.

Returns *InterceptedCommand

func (*InterceptedCommand) Execute

func (c *InterceptedCommand) Execute(correlationId string, args *run.Parameters) (result interface{}, err error)

Executes the next command in the execution chain using the given parameters (arguments). see Parameters Parameters:

  • correlationId: string unique transaction id to trace calls across components.
  • args: Parameters the parameters (arguments) to pass to the command for execution.

Returns: err: error result: interface{}

func (*InterceptedCommand) Name

func (c *InterceptedCommand) Name() string

Returns string the name of the command that is being intercepted.

func (*InterceptedCommand) Validate

Validates the parameters (arguments) that are to be passed to the command that is next in the execution chain. see Parameters see ValidationResult Parameters:

  • args: Parameters the parameters (arguments) to validate for the next command.

Returns []*ValidationResult an array of *ValidationResults.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL