github.com/oam-dev/kubevela@v1.9.11/pkg/cue/task/process.go (about)

     1  /*
     2  Copyright 2021 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package task
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  
    24  	"cuelang.org/go/cue"
    25  
    26  	"github.com/kubevela/workflow/pkg/cue/model/value"
    27  
    28  	"github.com/oam-dev/kubevela/pkg/builtin"
    29  	"github.com/oam-dev/kubevela/pkg/builtin/registry"
    30  )
    31  
    32  // Process processing the http task
    33  func Process(val cue.Value) (cue.Value, error) {
    34  	taskVal := val.LookupPath(value.FieldPath("processing", "http"))
    35  	if !taskVal.Exists() {
    36  		return val, errors.New("there is no http in processing")
    37  	}
    38  	resp, err := exec(taskVal)
    39  	if err != nil {
    40  		return val, fmt.Errorf("fail to exec http task, %w", err)
    41  	}
    42  
    43  	return val.FillPath(value.FieldPath("processing", "output"), resp), nil
    44  }
    45  
    46  func exec(v cue.Value) (map[string]interface{}, error) {
    47  	got, err := builtin.RunTaskByKey("http", cue.Value{}, &registry.Meta{Obj: v})
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	gotMap, ok := got.(map[string]interface{})
    52  	if !ok {
    53  		return nil, fmt.Errorf("fail to convert got to map")
    54  	}
    55  	body, ok := gotMap["body"].(string)
    56  	if !ok {
    57  		return nil, fmt.Errorf("fail to convert body to string")
    58  	}
    59  	resp := make(map[string]interface{})
    60  	if err := json.Unmarshal([]byte(body), &resp); err != nil {
    61  		return nil, err
    62  	}
    63  	return resp, nil
    64  }