bool.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package test_node
  2. import (
  3. "fmt"
  4. "git.sxidc.com/go-tools/utils/pipeline/component"
  5. "git.sxidc.com/go-tools/utils/strutils"
  6. "github.com/mitchellh/mapstructure"
  7. "github.com/pkg/errors"
  8. "math/rand"
  9. )
  10. const (
  11. TypeBool = "bool"
  12. )
  13. const (
  14. BoolOperationPass = "pass"
  15. BoolOperationReverse = "reverse"
  16. BoolOperationRand = "rand"
  17. BoolOperationUseLastResult = "last"
  18. )
  19. type BoolRunParams struct {
  20. Operation string `mapstructure:"op" structs:"op"`
  21. Value *bool `mapstructure:"value" structs:"value"`
  22. }
  23. type BoolNode struct {
  24. component.BaseComponent
  25. }
  26. func (n *BoolNode) Run(globalRunParams *component.GlobalRunParams, dynamicParams map[string]any) (any, error) {
  27. return n.OnRun(globalRunParams, dynamicParams,
  28. func(globalRunParams *component.GlobalRunParams, dynamicParams map[string]any) (any, error) {
  29. params := new(BoolRunParams)
  30. err := mapstructure.Decode(dynamicParams, params)
  31. if err != nil {
  32. return nil, errors.New(TypeBool + "节点运行时参数Decode失败: " + err.Error())
  33. }
  34. if strutils.IsStringEmpty(params.Operation) {
  35. params.Operation = BoolOperationPass
  36. }
  37. switch params.Operation {
  38. case BoolOperationPass:
  39. if params.Value == nil {
  40. return false, nil
  41. }
  42. return *params.Value, nil
  43. case BoolOperationReverse:
  44. if params.Value == nil {
  45. return false, nil
  46. }
  47. return !*params.Value, nil
  48. case BoolOperationRand:
  49. result := rand.Uint32()%2 == 0
  50. fmt.Println("rand bool is", result)
  51. return result, nil
  52. case BoolOperationUseLastResult:
  53. lastResult := globalRunParams.GetLastResult()
  54. lastResultBool, ok := lastResult.(bool)
  55. if !ok {
  56. return lastResult != nil, nil
  57. }
  58. return lastResultBool, nil
  59. default:
  60. return nil, errors.New(TypeBool + "不支持的操作: " + params.Operation)
  61. }
  62. })
  63. }
  64. type BoolBuilder struct{}
  65. func (builder *BoolBuilder) ProductType() string {
  66. return TypeBool
  67. }
  68. func (builder *BoolBuilder) Build(name string, _ map[string]any, runParams map[string]any) (component.Component, error) {
  69. return &BoolNode{
  70. BaseComponent: *component.NewBaseComponent(TypeBool, name, runParams),
  71. }, nil
  72. }