github.com/IBM-Cloud/bluemix-go@v0.0.0-20240423071914-9e96525baef4/api/resource/resourcev1/management/resource_quota.go (about)

     1  package management
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/IBM-Cloud/bluemix-go/bmxerror"
     7  	"github.com/IBM-Cloud/bluemix-go/client"
     8  	"github.com/IBM-Cloud/bluemix-go/models"
     9  )
    10  
    11  type quotaDefinitionQueryResult struct {
    12  	QuotaDefinitions []models.QuotaDefinition `json:"resources"`
    13  }
    14  
    15  //ErrCodeResourceQuotaDoesnotExist ...
    16  const ErrCodeResourceQuotaDoesnotExist = "ResourceQuotaDoesnotExist"
    17  
    18  type ResourceQuotaRepository interface {
    19  	// List all quota definitions
    20  	List() ([]models.QuotaDefinition, error)
    21  	// Query quota definitions having specific name
    22  	FindByName(name string) ([]models.QuotaDefinition, error)
    23  	// Get quota definition by ID
    24  	Get(id string) (*models.QuotaDefinition, error)
    25  }
    26  
    27  type resourceQuota struct {
    28  	client *client.Client
    29  }
    30  
    31  func newResourceQuotaAPI(c *client.Client) ResourceQuotaRepository {
    32  	return &resourceQuota{
    33  		client: c,
    34  	}
    35  }
    36  
    37  func (r *resourceQuota) List() ([]models.QuotaDefinition, error) {
    38  	resp := quotaDefinitionQueryResult{}
    39  	// TODO: change to use pagination if it's available on backend
    40  	_, err := r.client.Get("/v1/quota_definitions", &resp)
    41  	if err != nil {
    42  		return []models.QuotaDefinition{}, err
    43  	}
    44  	return resp.QuotaDefinitions, nil
    45  }
    46  
    47  func (r *resourceQuota) FindByName(name string) ([]models.QuotaDefinition, error) {
    48  	allQuotas, err := r.List()
    49  	if err != nil {
    50  		return []models.QuotaDefinition{}, err
    51  	}
    52  
    53  	quotas := []models.QuotaDefinition{}
    54  	for _, quota := range allQuotas {
    55  		if quota.Name == name {
    56  			quotas = append(quotas, quota)
    57  		}
    58  	}
    59  
    60  	if len(quotas) == 0 {
    61  		return quotas, bmxerror.New(ErrCodeResourceQuotaDoesnotExist,
    62  			fmt.Sprintf("Given quota : %q doesn't exist", name))
    63  	}
    64  
    65  	return quotas, nil
    66  }
    67  
    68  func (r *resourceQuota) Get(id string) (*models.QuotaDefinition, error) {
    69  	quota := models.QuotaDefinition{}
    70  	_, err := r.client.Get("/v1/quota_definitions/"+id, &quota)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	return &quota, nil
    75  }