github.com/elopio/cli@v6.21.2-0.20160902224010-ea909d1fdb2f+incompatible/cf/v3/repository/repository.go (about)

     1  package repository
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/url"
     6  
     7  	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
     8  	"code.cloudfoundry.org/cli/cf/v3/models"
     9  	"github.com/cloudfoundry/go-ccapi/v3/client"
    10  )
    11  
    12  //go:generate counterfeiter . Repository
    13  
    14  type Repository interface {
    15  	GetApplications() ([]models.V3Application, error)
    16  	GetProcesses(path string) ([]models.V3Process, error)
    17  	GetRoutes(path string) ([]models.V3Route, error)
    18  }
    19  
    20  type repository struct {
    21  	client client.Client
    22  	config coreconfig.ReadWriter
    23  }
    24  
    25  func NewRepository(config coreconfig.ReadWriter, client client.Client) Repository {
    26  	return &repository{
    27  		client: client,
    28  		config: config,
    29  	}
    30  }
    31  
    32  func (r *repository) handleUpdatedTokens() {
    33  	if r.client.TokensUpdated() {
    34  		accessToken, refreshToken := r.client.GetUpdatedTokens()
    35  		r.config.SetAccessToken(accessToken)
    36  		r.config.SetRefreshToken(refreshToken)
    37  	}
    38  }
    39  
    40  func (r *repository) GetApplications() ([]models.V3Application, error) {
    41  	jsonResponse, err := r.client.GetApplications(url.Values{})
    42  	if err != nil {
    43  		return []models.V3Application{}, err
    44  	}
    45  
    46  	r.handleUpdatedTokens()
    47  
    48  	applications := []models.V3Application{}
    49  	err = json.Unmarshal(jsonResponse, &applications)
    50  	if err != nil {
    51  		return []models.V3Application{}, err
    52  	}
    53  
    54  	return applications, nil
    55  }
    56  
    57  func (r *repository) GetProcesses(path string) ([]models.V3Process, error) {
    58  	jsonResponse, err := r.client.GetResources(path, 0)
    59  	if err != nil {
    60  		return []models.V3Process{}, err
    61  	}
    62  
    63  	r.handleUpdatedTokens()
    64  
    65  	processes := []models.V3Process{}
    66  	err = json.Unmarshal(jsonResponse, &processes)
    67  	if err != nil {
    68  		return []models.V3Process{}, err
    69  	}
    70  
    71  	return processes, nil
    72  }
    73  
    74  func (r *repository) GetRoutes(path string) ([]models.V3Route, error) {
    75  	jsonResponse, err := r.client.GetResources(path, 0)
    76  	if err != nil {
    77  		return []models.V3Route{}, err
    78  	}
    79  
    80  	r.handleUpdatedTokens()
    81  
    82  	routes := []models.V3Route{}
    83  	err = json.Unmarshal(jsonResponse, &routes)
    84  	if err != nil {
    85  		return []models.V3Route{}, err
    86  	}
    87  
    88  	return routes, nil
    89  }