get.porter.sh/porter@v1.3.0/pkg/storage/bundle.go (about) 1 package storage 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "strconv" 8 9 "github.com/cnabio/cnab-go/bundle" 10 ) 11 12 var _ json.Marshaler = BundleDocument{} 13 var _ json.Unmarshaler = &BundleDocument{} 14 15 // BundleDocument is the storage representation of a Bundle in mongo (as a string containing quoted json). 16 type BundleDocument bundle.Bundle 17 18 // MarshalJSON converts the bundle to a json string. 19 func (b BundleDocument) MarshalJSON() ([]byte, error) { 20 // Write the bundle definition to a string, so we can 21 // store it in mongo 22 var bunData bytes.Buffer 23 bun := bundle.Bundle(b) 24 if _, err := bun.WriteTo(&bunData); err != nil { 25 return nil, fmt.Errorf("error marshaling Bundle into its storage representation: %w", err) 26 } 27 28 bunStr := strconv.Quote(bunData.String()) 29 return []byte(bunStr), nil 30 } 31 32 // UnmarshalJSON converts the bundle from a json string. 33 func (b *BundleDocument) UnmarshalJSON(data []byte) error { 34 jsonData, err := strconv.Unquote(string(data)) 35 if err != nil { 36 return fmt.Errorf("error unquoting Bundle from its storage representation: %w", err) 37 } 38 var rawBun bundle.Bundle 39 if err := json.Unmarshal([]byte(jsonData), &rawBun); err != nil { 40 return fmt.Errorf("error unmarshaling Bundle from its storage representation: %w", err) 41 } 42 43 *b = BundleDocument(rawBun) 44 return nil 45 }