jx/internal/resource/document.go
Matthew Rich 5a49359722
Some checks failed
Lint / golangci-lint (push) Failing after 10m8s
Declarative Tests / test (push) Successful in 54s
add encoder/decoder support for json and yaml
add support for jsonschema verification
2024-04-03 09:54:50 -07:00

97 lines
2.0 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"encoding/json"
"errors"
_ "fmt"
"github.com/xeipuuv/gojsonschema"
"gopkg.in/yaml.v3"
"io"
_ "log"
_ "net/url"
"strings"
)
type Document struct {
ResourceDecls []Declaration `json:"resources" yaml:"resources"`
}
func NewDocument() *Document {
return &Document{}
}
func (d *Document) Load(r io.Reader) error {
yamlDecoder := yaml.NewDecoder(r)
if e := yamlDecoder.Decode(d); e != nil {
return e
}
return nil
}
func (d *Document) Validate() error {
jsonDocument, jsonErr := d.JSON()
if jsonErr == nil {
schemaLoader := gojsonschema.NewReferenceLoader("file://schemas/document.jsonschema")
documentLoader := gojsonschema.NewBytesLoader(jsonDocument)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return err
}
if !result.Valid() {
schemaErrors := strings.Builder{}
for _, err := range result.Errors() {
schemaErrors.WriteString(err.String() + "\n")
}
return errors.New(schemaErrors.String())
}
}
return nil
}
func (d *Document) Resources() []Declaration {
return d.ResourceDecls
}
func (d *Document) Apply() error {
for i := range d.ResourceDecls {
if e := d.ResourceDecls[i].Resource().Apply(); e != nil {
return e
}
}
return nil
}
func (d *Document) Generate(w io.Writer) error {
e := NewYAMLEncoder(w)
e.Encode(d)
return e.Close()
}
func (d *Document) AddResourceDeclaration(resourceType string, resourceDeclaration Resource) {
decl := NewDeclaration()
decl.Type = TypeName(resourceType)
decl.Attributes = resourceDeclaration
d.ResourceDecls = append(d.ResourceDecls, *decl)
}
func (d *Document) AddResource(uri string) error {
//parsedResourceURI, e := url.Parse(uri)
//if e == nil {
decl := NewDeclaration()
decl.SetURI(uri)
d.ResourceDecls = append(d.ResourceDecls, *decl)
//}
return nil
}
func (d *Document) JSON() ([]byte, error) {
return json.Marshal(d)
}
func (d *Document) YAML() ([]byte, error) {
return yaml.Marshal(d)
}