github.com/TIBCOSoftware/flogo-lib@v0.5.9/core/data/mapping.go (about)

     1  package data
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  )
     7  
     8  // MappingType is an enum for possible MappingDef Types
     9  type MappingType int
    10  
    11  const (
    12  	// MtAssign denotes an attribute to attribute assignment
    13  	MtAssign MappingType = 1
    14  
    15  	// MtLiteral denotes a literal to attribute assignment
    16  	MtLiteral MappingType = 2
    17  
    18  	// MtExpression denotes a expression execution to perform mapping
    19  	MtExpression MappingType = 3
    20  
    21  	// MtObject denotes a object construction mapping
    22  	MtObject MappingType = 4
    23  
    24  	MtArray MappingType = 5
    25  )
    26  
    27  // MappingDef is a simple structure that defines a mapping
    28  type MappingDef struct {
    29  	//Type the mapping type
    30  	Type MappingType
    31  
    32  	//Value the mapping value to execute to determine the result (rhs)
    33  	Value interface{}
    34  
    35  	//Result the name of attribute to place the result of the mapping in (lhs)
    36  	MapTo string
    37  }
    38  
    39  // Mapper is a constructs that maps values from one scope to another
    40  type Mapper interface {
    41  	Apply(inputScope Scope, outputScope Scope) error
    42  }
    43  
    44  // MapperDef represents a Mapper, which is a collection of mappings
    45  type MapperDef struct {
    46  	//todo possibly add optional lang/mapper type so we can fast fail on unsupported mappings/mapper combo
    47  	Mappings []*MappingDef
    48  }
    49  
    50  type IOMappings struct {
    51  	Input  []*MappingDef `json:"input,omitempty"`
    52  	Output []*MappingDef `json:"output,omitempty"`
    53  }
    54  
    55  func (md *MappingDef) UnmarshalJSON(b []byte) error {
    56  
    57  	ser := &struct {
    58  		Type  interface{} `json:"type"`
    59  		Value interface{} `json:"value"`
    60  		MapTo string      `json:"mapTo"`
    61  	}{}
    62  
    63  	if err := json.Unmarshal(b, ser); err != nil {
    64  		return err
    65  	}
    66  
    67  	md.MapTo = ser.MapTo
    68  	md.Value = ser.Value
    69  	intType, err := ConvertMappingType(ser.Type)
    70  	if err == nil {
    71  		md.Type = intType
    72  	}
    73  	return err
    74  }
    75  
    76  func ConvertMappingType(mapType interface{}) (MappingType, error) {
    77  	strType, _ := CoerceToString(mapType)
    78  	switch strType {
    79  	case "assign", "1":
    80  		return MtAssign, nil
    81  	case "literal", "2":
    82  		return MtLiteral, nil
    83  	case "expression", "3":
    84  		return MtExpression, nil
    85  	case "object", "4":
    86  		return MtObject, nil
    87  	case "array", "5":
    88  		return MtArray, nil
    89  	default:
    90  		return 0, errors.New("unsupported mapping type: " + strType)
    91  	}
    92  }