| 1 |
// Copyright 2025 Princess B33f Heavy Industries / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package openapi_vocabulary |
| 5 |
|
| 6 |
import ( |
| 7 |
"github.com/santhosh-tekuri/jsonschema/v6" |
| 8 |
) |
| 9 |
|
| 10 |
// discriminatorExtension handles the OpenAPI discriminator keyword |
| 11 |
type discriminatorExtension struct { |
| 12 |
propertyName string |
| 13 |
mapping map[string]string // value -> schema reference |
| 14 |
} |
| 15 |
|
| 16 |
// Validate validates the discriminator property exists in the instance |
| 17 |
func (d *discriminatorExtension) Validate(ctx *jsonschema.ValidatorContext, v any) { |
| 18 |
obj, _ := v.(map[string]any) |
| 19 |
|
| 20 |
// check if discriminator property exists in the object |
| 21 |
if d.propertyName != "" { |
| 22 |
if _, exists := obj[d.propertyName]; !exists { |
| 23 |
ctx.AddError(&DiscriminatorPropertyMissingError{ |
| 24 |
PropertyName: d.propertyName, |
| 25 |
}) |
| 26 |
} |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
// CompileDiscriminator compiles the OpenAPI discriminator keyword |
| 31 |
func CompileDiscriminator(_ *jsonschema.CompilerContext, obj map[string]any, _ VersionType) (jsonschema.SchemaExt, error) { |
| 32 |
v, exists := obj["discriminator"] |
| 33 |
if !exists { |
| 34 |
return nil, nil |
| 35 |
} |
| 36 |
|
| 37 |
discriminator, ok := v.(map[string]any) |
| 38 |
if !ok { |
| 39 |
return nil, &OpenAPIKeywordError{ |
| 40 |
Keyword: "discriminator", |
| 41 |
Message: "discriminator must be an object", |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
propertyNameValue, exists := discriminator["propertyName"] |
| 46 |
if !exists { |
| 47 |
return nil, &OpenAPIKeywordError{ |
| 48 |
Keyword: "discriminator", |
| 49 |
Message: "discriminator must have a propertyName field", |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
propertyName, ok := propertyNameValue.(string) |
| 54 |
if !ok { |
| 55 |
return nil, &OpenAPIKeywordError{ |
| 56 |
Keyword: "discriminator", |
| 57 |
Message: "discriminator propertyName must be a string", |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
var mapping map[string]string |
| 62 |
if mappingValue, exists := discriminator["mapping"]; exists { |
| 63 |
mappingObj, ok := mappingValue.(map[string]any) |
| 64 |
if !ok { |
| 65 |
return nil, &OpenAPIKeywordError{ |
| 66 |
Keyword: "discriminator", |
| 67 |
Message: "discriminator mapping must be an object", |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
mapping = make(map[string]string) |
| 72 |
for key, value := range mappingObj { |
| 73 |
if strValue, ok := value.(string); ok { |
| 74 |
mapping[key] = strValue |
| 75 |
} else { |
| 76 |
return nil, &OpenAPIKeywordError{ |
| 77 |
Keyword: "discriminator", |
| 78 |
Message: "discriminator mapping values must be strings", |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
return &discriminatorExtension{ |
| 85 |
propertyName: propertyName, |
| 86 |
mapping: mapping, |
| 87 |
}, nil |
| 88 |
} |