55 lines
1.0 KiB
Go
55 lines
1.0 KiB
Go
package block
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"regexp"
|
|
)
|
|
|
|
var validSlug = regexp.MustCompile(`^[a-z0-9]+$`)
|
|
|
|
type Block struct {
|
|
Slug string
|
|
Components []Component
|
|
}
|
|
|
|
func NewBlock(slug string, components []Component) (*Block, error) {
|
|
if !validSlug.MatchString(slug) {
|
|
return nil, fmt.Errorf("invalid block slug %q: must be a-z0-9 only", slug)
|
|
}
|
|
return &Block{Slug: slug, Components: components}, nil
|
|
}
|
|
|
|
type BlockInstance struct {
|
|
Components []ComponentInstance
|
|
}
|
|
|
|
func (b *BlockInstance) FromJSON(block *Block, data []byte) error {
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
return err
|
|
}
|
|
|
|
var components []ComponentInstance
|
|
|
|
for _, c := range block.Components {
|
|
jsonValue, ok := raw[c.Identifier()]
|
|
// jsonValue, ok := raw[c.Identifier()]
|
|
if !ok {
|
|
// continue
|
|
jsonValue = nil
|
|
}
|
|
instance := c.NewInstance()
|
|
|
|
if err := instance.FromJSON(c, jsonValue); err != nil {
|
|
return err
|
|
}
|
|
|
|
components = append(components, instance)
|
|
}
|
|
|
|
b.Components = components
|
|
|
|
return nil
|
|
}
|