github.com/Jeffail/benthos/v3@v3.65.0/public/service/config_bloblang.go (about)

     1  package service
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/Jeffail/benthos/v3/internal/docs"
     8  	"github.com/Jeffail/benthos/v3/public/bloblang"
     9  )
    10  
    11  // NewBloblangField defines a new config field that describes a Bloblang mapping
    12  // string. It is then possible to extract a *bloblang.Executor from the
    13  // resulting parsed config with the method FieldBloblang.
    14  func NewBloblangField(name string) *ConfigField {
    15  	tf := docs.FieldBloblang(name, "")
    16  	return &ConfigField{field: tf}
    17  }
    18  
    19  // FieldBloblang accesses a field from a parsed config that was defined with
    20  // NewBloblangField and returns either a *bloblang.Executor or an error if the
    21  // mapping was invalid.
    22  func (p *ParsedConfig) FieldBloblang(path ...string) (*bloblang.Executor, error) {
    23  	v, exists := p.field(path...)
    24  	if !exists {
    25  		return nil, fmt.Errorf("field '%v' was not found in the config", strings.Join(path, "."))
    26  	}
    27  
    28  	str, ok := v.(string)
    29  	if !ok {
    30  		return nil, fmt.Errorf("expected field '%v' to be a string, got %T", strings.Join(path, "."), v)
    31  	}
    32  
    33  	exec, err := bloblang.XWrapEnvironment(p.mgr.BloblEnvironment()).Parse(str)
    34  	if err != nil {
    35  		return nil, fmt.Errorf("failed to parse bloblang mapping '%v': %v", strings.Join(path, "."), err)
    36  	}
    37  	return exec, nil
    38  }