Files
threshold/api/internal/genapi/read.go
T
Todd Knight d374ac6d4c Handler hostcatalogs sdk (#103)
* Created host catalog service.

* Fixing uri generation for create.

* Use newly submitted static host catalog.

* Copying over tests from projects.

* Fix UpdateHostCatalogRequest merging proto.

* Properly use static host catalog prefixes in tests.

* Correct test to verify the expected uri and id prefix is set.

* Add test for unsetting descriptions.

* Correct bad spelling in comment.

* Tweaking variable names.

* Adding Stringer to the catalog type and setting the type on the response.

* Setting up the catalogType to contain more info regarding its type.

* Validate the type field in requests.

* Remove unused method.

* Comment describing invariants around types.

* Wiring in the repo into the static catalog handler.

* feature:  Add CRUD operations for host catalogs to the go api library.

* Updated comments to the exported methods.

* fix: return the result of handlers.NotFoundError instead of just calling it.

* Fixing typos referencing just hosts instead of host catlogs.

* Update NewService returns an error and a non pointer type.

* Pull "org_id" and "project_id" into constants and the validation of them into the ValidateAncestors.

* Check errors for all Register*HandlerServer calls.

* fix: Remove left over reference that could cause a panic.

* fix: Changing "x := []string{}" to "var x []string"

* fix: Log errors in test cleanup.

* Changing the code to use google.golang.org/protobuf instead of the older github based protobuf library.

* Changing all t.Fatal checks to require.NoError calls.

* Changing unrecognized prefixes to Invalid Argument instead of Not Found.

* fix: toDbUpdateMask now returns error if it was unable to find any valid paths.

* Define CreatedTime, UpdatedTime, and Type at initialization time in toProto.

* Adding sdk test for unsetting a value.

* Require that project is created correctly before testing the catalog.

* Remove unused host catalog from test.

* Change a t.Fatal to a require.NoError that I missed earlier.

* Change shutdown error logging to t.Errorfs.

* Shorten validateX function names.

* Inline API responses.

* Add todo to make a new repo per request.

* Inline regex check for invalid id.

* Change stored repos into repo creating functions which satisfies ICU-223.

* Wrap proto comments to be under 80 characters long.

* Remove the exception on the read only fields that can be set in an Update request.

* Removing out of date comment.

* Use iam.TestScopes instead of making the project myself.

* Renaming files to be consistant with go test standards and resource naming standards.

* Remove TODO related to a task completed in an earlier commit.

* Fix the previous commit which removed the wrong TODO.
2020-06-05 13:02:58 -07:00

118 lines
3.1 KiB
Go

package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"text/template"
)
type readInfo struct {
baseType string
targetType string
path string
}
var readFuncs = map[string][]*readInfo{
"scopes": {
{
baseType: "Organization",
targetType: "Project",
path: "projects",
},
{
baseType: "Project",
targetType: "hosts.HostCatalog",
path: "host-catalogs",
},
},
}
func writeReadFuncs() {
for outPkg, funcs := range readFuncs {
outFile := os.Getenv("GEN_BASEPATH") + fmt.Sprintf("/api/%s/read.gen.go", outPkg)
outBuf := bytes.NewBuffer([]byte(fmt.Sprintf(
`// Code generated by "make api"; DO NOT EDIT.
package %s
`, outPkg)))
for _, readInfo := range funcs {
readFuncTemplate.Execute(outBuf, struct {
BaseType string
TargetType string
TargetName string
Path string
}{
BaseType: readInfo.baseType,
TargetType: readInfo.targetType,
TargetName: strings.Split(readInfo.targetType, ".")[strings.Count(readInfo.targetType, ".")],
Path: readInfo.path,
})
}
if err := ioutil.WriteFile(outFile, outBuf.Bytes(), 0644); err != nil {
fmt.Printf("error writing file %q: %v\n", outFile, err)
os.Exit(1)
}
}
}
var readFuncTemplate = template.Must(template.New("").Parse(
`
func (s {{ .BaseType }}) Read{{ .TargetName }}(ctx context.Context, r *{{ .TargetType }}) (*{{ .TargetType }}, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in Read{{ .TargetName }} request")
}
if s.Id == "" {
{{ if (eq .BaseType "Organization") }}
// Assume the client has been configured with organization already and
// move on
{{ else if (eq .BaseType "Project") }}
// Assume the client has been configured with project already and move
// on
{{ else }}
return nil, nil, fmt.Errorf("missing {{ .BaseType }} ID in Read{{ .TargetType }} request")
{{ end }}
} else {
// If it's explicitly set here, override anything that might be in the
// client
{{ if (eq .BaseType "Organization") }}
ctx = context.WithValue(ctx, "org", s.Id)
{{ else if (eq .BaseType "Project") }}
ctx = context.WithValue(ctx, "project", s.Id)
{{ end }}
}
if r.Id == "" {
return nil, nil, fmt.Errorf("empty {{ .TargetType }} ID field in Read{{ .TargetName }} request")
}
req, err := s.Client.NewRequest(ctx, "GET", fmt.Sprintf("%s/%s", "{{ .Path }}", r.Id), r)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read{{ .TargetName }} request: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read{{ .TargetName }} call: %w", err)
}
target := new({{ .TargetType }})
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read{{ .TargetName }} repsonse: %w", err)
}
{{ if (eq .TargetType "Organization") }}
target.Client = s.Client.Clone()
target.Client.SetOrgnization(target.Id)
{{ else if (eq .TargetType "Project") }}
target.Client = s.Client.Clone()
target.Client.SetProject(target.Id)
{{ else }}
target.Client = s.Client
{{ end }}
return target, apiErr, nil
}
`))