github.com/kubeshop/testkube@v1.17.23/pkg/tcl/apitcl/v1/utils.go (about)

     1  // Copyright 2024 Testkube.
     2  //
     3  // Licensed as a Testkube Pro file under the Testkube Community
     4  // License (the "License"); you may not use this file except in compliance with
     5  // the License. You may obtain a copy of the License at
     6  //
     7  //	https://github.com/kubeshop/testkube/blob/main/licenses/TCL.txt
     8  
     9  package v1
    10  
    11  import (
    12  	"github.com/gofiber/fiber/v2"
    13  	"github.com/pkg/errors"
    14  	"go.mongodb.org/mongo-driver/mongo"
    15  	"google.golang.org/grpc/codes"
    16  	"google.golang.org/grpc/status"
    17  	k8serrors "k8s.io/apimachinery/pkg/api/errors"
    18  	"k8s.io/apimachinery/pkg/runtime/schema"
    19  
    20  	"github.com/kubeshop/testkube/internal/common"
    21  )
    22  
    23  const (
    24  	mediaTypeJSON      = "application/json"
    25  	mediaTypeYAML      = "text/yaml"
    26  	mediaTypePlainText = "text/plain"
    27  )
    28  
    29  func ExpectsYAML(c *fiber.Ctx) bool {
    30  	return c.Accepts(mediaTypeJSON, mediaTypeYAML) == mediaTypeYAML || c.Query("_yaml") == "true"
    31  }
    32  
    33  func HasYAML(c *fiber.Ctx) bool {
    34  	return string(c.Request().Header.ContentType()) == mediaTypeYAML
    35  }
    36  
    37  func SendResourceList[T interface{}, U interface{}](c *fiber.Ctx, kind string, groupVersion schema.GroupVersion, jsonMapper func(T) U, data ...T) error {
    38  	if ExpectsYAML(c) {
    39  		return SendCRDs(c, kind, groupVersion, data...)
    40  	}
    41  	result := make([]U, len(data))
    42  	for i, item := range data {
    43  		result[i] = jsonMapper(item)
    44  	}
    45  	return c.JSON(result)
    46  }
    47  
    48  func SendResource[T interface{}, U interface{}](c *fiber.Ctx, kind string, groupVersion schema.GroupVersion, jsonMapper func(T) U, data T) error {
    49  	if ExpectsYAML(c) {
    50  		return SendCRDs(c, kind, groupVersion, data)
    51  	}
    52  	return c.JSON(jsonMapper(data))
    53  }
    54  
    55  func SendCRDs[T interface{}](c *fiber.Ctx, kind string, groupVersion schema.GroupVersion, crds ...T) error {
    56  	b, err := common.SerializeCRDs(crds, common.SerializeOptions{
    57  		OmitCreationTimestamp: true,
    58  		CleanMeta:             true,
    59  		Kind:                  kind,
    60  		GroupVersion:          &groupVersion,
    61  	})
    62  	if err != nil {
    63  		return err
    64  	}
    65  	c.Context().SetContentType(mediaTypeYAML)
    66  	return c.Send(b)
    67  }
    68  
    69  func IsNotFound(err error) bool {
    70  	if err == nil {
    71  		return false
    72  	}
    73  	if errors.Is(err, mongo.ErrNoDocuments) || k8serrors.IsNotFound(err) {
    74  		return true
    75  	}
    76  	if e, ok := status.FromError(err); ok {
    77  		return e.Code() == codes.NotFound
    78  	}
    79  	return false
    80  }