github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/api/stacks/stacks.go (about) 1 package stacks 2 3 import ( 4 "fmt" 5 "net/url" 6 7 "code.cloudfoundry.org/cli/cf/api/resources" 8 "code.cloudfoundry.org/cli/cf/configuration/coreconfig" 9 "code.cloudfoundry.org/cli/cf/errors" 10 "code.cloudfoundry.org/cli/cf/models" 11 "code.cloudfoundry.org/cli/cf/net" 12 13 . "code.cloudfoundry.org/cli/cf/i18n" 14 ) 15 16 //go:generate counterfeiter . StackRepository 17 18 type StackRepository interface { 19 FindByName(name string) (stack models.Stack, apiErr error) 20 FindByGUID(guid string) (models.Stack, error) 21 FindAll() (stacks []models.Stack, apiErr error) 22 } 23 24 type CloudControllerStackRepository struct { 25 config coreconfig.Reader 26 gateway net.Gateway 27 } 28 29 func NewCloudControllerStackRepository(config coreconfig.Reader, gateway net.Gateway) (repo CloudControllerStackRepository) { 30 repo.config = config 31 repo.gateway = gateway 32 return 33 } 34 35 func (repo CloudControllerStackRepository) FindByGUID(guid string) (models.Stack, error) { 36 stackRequest := resources.StackResource{} 37 path := fmt.Sprintf("%s/v2/stacks/%s", repo.config.APIEndpoint(), guid) 38 err := repo.gateway.GetResource(path, &stackRequest) 39 if err != nil { 40 if errNotFound, ok := err.(*errors.HTTPNotFoundError); ok { 41 return models.Stack{}, errNotFound 42 } 43 44 return models.Stack{}, fmt.Errorf(T("Error retrieving stacks: {{.Error}}", map[string]interface{}{ 45 "Error": err.Error(), 46 })) 47 } 48 49 return *stackRequest.ToFields(), nil 50 } 51 52 func (repo CloudControllerStackRepository) FindByName(name string) (stack models.Stack, apiErr error) { 53 path := fmt.Sprintf("/v2/stacks?q=%s", url.QueryEscape("name:"+name)) 54 stacks, apiErr := repo.findAllWithPath(path) 55 if apiErr != nil { 56 return 57 } 58 59 if len(stacks) == 0 { 60 apiErr = errors.NewModelNotFoundError("Stack", name) 61 return 62 } 63 64 stack = stacks[0] 65 return 66 } 67 68 func (repo CloudControllerStackRepository) FindAll() (stacks []models.Stack, apiErr error) { 69 return repo.findAllWithPath("/v2/stacks") 70 } 71 72 func (repo CloudControllerStackRepository) findAllWithPath(path string) ([]models.Stack, error) { 73 var stacks []models.Stack 74 apiErr := repo.gateway.ListPaginatedResources( 75 repo.config.APIEndpoint(), 76 path, 77 resources.StackResource{}, 78 func(resource interface{}) bool { 79 if sr, ok := resource.(resources.StackResource); ok { 80 stacks = append(stacks, *sr.ToFields()) 81 } 82 return true 83 }) 84 return stacks, apiErr 85 }