Skip to content

Commit

Permalink
feat: add custom strfmt.Registry support
Browse files Browse the repository at this point in the history
Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
  • Loading branch information
eddycharly committed May 11, 2023
1 parent 2160781 commit 62fe864
Showing 1 changed file with 34 additions and 7 deletions.
41 changes: 34 additions & 7 deletions pkg/validatorfactory/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,36 @@ import (

type ValidatorFactory struct {
gvs map[string]openapi.GroupVersion
registry strfmt.Registry
validatorCache map[schema.GroupVersionKind]*ValidatorEntry
}

type ValidatorEntry struct {
*spec.Schema
name string
structuralSchemaFactory structuralSchemaFactory
registry strfmt.Registry
schemaValidator *validate.SchemaValidator
ss *structuralschema.Structural
}

func newValidatorEntry(name string, openapiSchema *spec.Schema, ssf structuralSchemaFactory) *ValidatorEntry {
return &ValidatorEntry{Schema: openapiSchema, name: name, structuralSchemaFactory: ssf}
func newValidatorEntry(name string, openapiSchema *spec.Schema, ssf structuralSchemaFactory, registry strfmt.Registry) *ValidatorEntry {
if registry == nil {
registry = strfmt.Default
}
return &ValidatorEntry{
Schema: openapiSchema,
name: name,
structuralSchemaFactory: ssf,
registry: registry,
}
}

func (v *ValidatorEntry) SchemaValidator() *validate.SchemaValidator {
if v.schemaValidator != nil {
return v.schemaValidator
}

v.schemaValidator = validate.NewSchemaValidator(v.Schema, nil, "", strfmt.Default)
v.schemaValidator = validate.NewSchemaValidator(v.Schema, nil, "", v.registry)
return v.schemaValidator
}

Expand Down Expand Up @@ -140,14 +149,32 @@ func (v *ValidatorEntry) StructuralSchema() (*structuralschema.Structural, error
// return v.celValidator, nil
// }

func New(client openapi.Client) (*ValidatorFactory, error) {
type factoryOptions struct {
registry strfmt.Registry
}

type factoryOption = func(*factoryOptions)

func WithRegistry(r strfmt.Registry) factoryOption {
return func(o *factoryOptions) {
o.registry = r
}
}

func New(client openapi.Client, options ...factoryOption) (*ValidatorFactory, error) {
gvs, err := client.Paths()
if err != nil {
return nil, err
}

var factoryOptions factoryOptions
for _, option := range options {
if option != nil {
option(&factoryOptions)
}
}
return &ValidatorFactory{
gvs: gvs,
registry: factoryOptions.registry,
validatorCache: map[schema.GroupVersionKind]*ValidatorEntry{},
}, nil
}
Expand Down Expand Up @@ -284,7 +311,7 @@ func (s *ValidatorFactory) ValidatorsForGVK(gvk schema.GroupVersionKind) (*Valid
continue
}

val := newValidatorEntry(nam, def, ssf)
val := newValidatorEntry(nam, def, ssf, s.registry)

for _, specGVK := range gvksList {
if stringMap, ok := specGVK.(map[string]string); ok {
Expand Down

0 comments on commit 62fe864

Please sign in to comment.