github.com/asifdxtreme/cli@v6.1.3-0.20150123051144-9ead8700b4ae+incompatible/cf/api/stacks/stacks.go (about)

     1  package stacks
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  
     7  	"github.com/cloudfoundry/cli/cf/api/resources"
     8  	"github.com/cloudfoundry/cli/cf/configuration/core_config"
     9  	"github.com/cloudfoundry/cli/cf/errors"
    10  	"github.com/cloudfoundry/cli/cf/models"
    11  	"github.com/cloudfoundry/cli/cf/net"
    12  )
    13  
    14  type StackRepository interface {
    15  	FindByName(name string) (stack models.Stack, apiErr error)
    16  	FindAll() (stacks []models.Stack, apiErr error)
    17  }
    18  
    19  type CloudControllerStackRepository struct {
    20  	config  core_config.Reader
    21  	gateway net.Gateway
    22  }
    23  
    24  func NewCloudControllerStackRepository(config core_config.Reader, gateway net.Gateway) (repo CloudControllerStackRepository) {
    25  	repo.config = config
    26  	repo.gateway = gateway
    27  	return
    28  }
    29  
    30  func (repo CloudControllerStackRepository) FindByName(name string) (stack models.Stack, apiErr error) {
    31  	path := fmt.Sprintf("/v2/stacks?q=%s", url.QueryEscape("name:"+name))
    32  	stacks, apiErr := repo.findAllWithPath(path)
    33  	if apiErr != nil {
    34  		return
    35  	}
    36  
    37  	if len(stacks) == 0 {
    38  		apiErr = errors.NewModelNotFoundError("Stack", name)
    39  		return
    40  	}
    41  
    42  	stack = stacks[0]
    43  	return
    44  }
    45  
    46  func (repo CloudControllerStackRepository) FindAll() (stacks []models.Stack, apiErr error) {
    47  	return repo.findAllWithPath("/v2/stacks")
    48  }
    49  
    50  func (repo CloudControllerStackRepository) findAllWithPath(path string) ([]models.Stack, error) {
    51  	var stacks []models.Stack
    52  	apiErr := repo.gateway.ListPaginatedResources(
    53  		repo.config.ApiEndpoint(),
    54  		path,
    55  		resources.StackResource{},
    56  		func(resource interface{}) bool {
    57  			if sr, ok := resource.(resources.StackResource); ok {
    58  				stacks = append(stacks, *sr.ToFields())
    59  			}
    60  			return true
    61  		})
    62  	return stacks, apiErr
    63  }