github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/events/handler/handler.go (about)

     1  package events
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/kyma-project/kyma-environment-broker/common/events"
     9  	"github.com/kyma-project/kyma-environment-broker/internal/storage"
    10  	"github.com/kyma-project/kyma-environment-broker/internal/storage/dbmodel"
    11  )
    12  
    13  type Handler struct {
    14  	e storage.Events
    15  	i storage.Instances
    16  }
    17  
    18  func NewHandler(e storage.Events, i storage.Instances) Handler {
    19  	return Handler{e, i}
    20  }
    21  
    22  func split(s string) []string {
    23  	if s == "" {
    24  		return []string{}
    25  	}
    26  	return strings.Split(s, ",")
    27  }
    28  
    29  func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    30  	instanceId := r.URL.Query().Get("instance_ids")
    31  	instanceIds := split(instanceId)
    32  	runtimeId := r.URL.Query().Get("runtime_ids")
    33  	operationId := r.URL.Query().Get("operation_ids")
    34  	operationIds := split(operationId)
    35  	if runtimeId != "" {
    36  		instances, _, _, err := h.i.List(dbmodel.InstanceFilter{RuntimeIDs: split(runtimeId)})
    37  		if err != nil {
    38  			http.Error(w, err.Error(), 503)
    39  			return
    40  		}
    41  		for _, i := range instances {
    42  			instanceIds = append(instanceIds, i.InstanceID)
    43  		}
    44  	}
    45  	events, err := h.e.ListEvents(events.EventFilter{InstanceIDs: instanceIds, OperationIDs: operationIds})
    46  	if err != nil {
    47  		http.Error(w, err.Error(), 503)
    48  		return
    49  	}
    50  	bytes, err := json.Marshal(events)
    51  	if err != nil {
    52  		http.Error(w, err.Error(), 503)
    53  		return
    54  	}
    55  	if _, err = w.Write(bytes); err != nil {
    56  		http.Error(w, err.Error(), 503)
    57  	}
    58  }