github.com/Datadog/cnab-go@v0.3.3-beta1.0.20191007143216-bba4b7e723d0/bundle/definition/validators.go (about)

     1  package definition
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  
     7  	"github.com/qri-io/jsonschema"
     8  )
     9  
    10  // ContentEncoding represents a "custom" Schema property
    11  type ContentEncoding string
    12  
    13  // NewContentEncoding allocates a new ContentEncoding validator
    14  func NewContentEncoding() jsonschema.Validator {
    15  	return new(ContentEncoding)
    16  }
    17  
    18  // Validate implements the Validator interface for ContentEncoding
    19  // which, as of writing, isn't included by default in the jsonschema library we consume
    20  func (c ContentEncoding) Validate(propPath string, data interface{}, errs *[]jsonschema.ValError) {
    21  	if obj, ok := data.(string); ok {
    22  		switch c {
    23  		case "base64":
    24  			_, err := base64.StdEncoding.DecodeString(obj)
    25  			if err != nil {
    26  				jsonschema.AddError(errs, propPath, data, fmt.Sprintf("invalid %s value: %s", c, obj))
    27  			}
    28  		// Add validation support for other encodings as needed
    29  		// See https://json-schema.org/latest/json-schema-validation.html#rfc.section.8.3
    30  		default:
    31  			jsonschema.AddError(errs, propPath, data, fmt.Sprintf("unsupported or invalid contentEncoding type of %s", c))
    32  		}
    33  	}
    34  }
    35  
    36  // NewRootSchema returns a jsonschema.RootSchema with any needed custom
    37  // jsonschema.Validators pre-registered
    38  func NewRootSchema() *jsonschema.RootSchema {
    39  	// Register custom validators here
    40  	// Note: as of writing, jsonschema doesn't have a stock validator for instances of type `contentEncoding`
    41  	// There may be others missing in the library that exist in http://json-schema.org/draft-07/schema#
    42  	// and thus, we'd need to create/register them here (if not included upstream)
    43  	jsonschema.RegisterValidator("contentEncoding", NewContentEncoding)
    44  	return new(jsonschema.RootSchema)
    45  }