Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OpenAPI: Add discriminators #80

Merged
merged 7 commits into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions internal/ast/compiler/disjunctions.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,14 +430,15 @@ func (pass *DisjunctionToType) buildDiscriminatorMapping(schema *ast.Schema, def
if field.Type.Kind != ast.KindScalar {
return nil, fmt.Errorf("discriminator field is not a scalar: %w", ErrCanNotInferDiscriminator)
}
if !field.Type.AsScalar().IsConcrete() {

switch {
case field.Type.AsScalar().IsConcrete():
mapping[field.Type.AsScalar().Value.(string)] = typeName
case field.Type.Default != nil:
mapping[field.Type.Default.(string)] = typeName
default:
return nil, fmt.Errorf("discriminator field is not concrete: %w", ErrCanNotInferDiscriminator)
}
if field.Type.AsScalar().ScalarKind != ast.KindString {
return nil, fmt.Errorf("discriminator field is not a string: %w", ErrCanNotInferDiscriminator)
}

mapping[field.Type.AsScalar().Value.(string)] = typeName
}

return mapping, nil
Expand Down
11 changes: 11 additions & 0 deletions internal/ast/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,17 @@ func Value(value any) TypeOption {
}
}

func Discriminator(discriminator string, mapping map[string]string) TypeOption {
return func(def *Type) {
if def.Kind != KindDisjunction {
return
}

def.Disjunction.Discriminator = discriminator
def.Disjunction.DiscriminatorMapping = mapping
}
}

func Any() Type {
return NewScalar(KindAny)
}
Expand Down
4 changes: 3 additions & 1 deletion internal/jennies/typescript/jennies.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ func Jennies() *codejen.JennyList[[]*ast.Schema] {
}

func CompilerPasses() []compiler.Pass {
return nil
return []compiler.Pass{
&compiler.PrefixEnumValues{},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need that for typescript? 🤔

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because I saw the same problem with the integer enums and they are setting number as names and they are invalid.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then I think we should probably have a different compiler pass, specifically for that use-case :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is working as expected... what is the difference?

}
}

func Veneers() *veneers.Rewriter {
Expand Down
37 changes: 19 additions & 18 deletions internal/openapi/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ package openapi

import (
"context"
"errors"
"fmt"
"strings"

"github.com/getkin/kin-openapi/openapi3"
"github.com/grafana/cog/internal/ast"
Expand Down Expand Up @@ -102,9 +100,6 @@ func (g *generator) walkDefinitions(schema *openapi3.Schema) (ast.Type, error) {
if schema.Enum != nil {
return g.walkEnum(schema)
}
if schema.Not != nil {
return g.walkNot(schema)
}

switch schema.Type {
case openapi3.TypeString:
Expand All @@ -128,10 +123,9 @@ func (g *generator) walkDefinitions(schema *openapi3.Schema) (ast.Type, error) {
func (g *generator) walkRef(ref string) (ast.Type, error) {
// TODO: Its assuming that we are referencing an object in the same document
// See https://swagger.io/specification/v3/#reference-object
parts := strings.Split(ref, "/")
referredKindName := parts[len(parts)-1]
referredKindName := getRefName(ref)

return ast.NewRef("", referredKindName), nil
return ast.NewRef(g.schema.Package, referredKindName), nil
}

func (g *generator) walkObject(schema *openapi3.Schema) (ast.Type, error) {
Expand Down Expand Up @@ -220,18 +214,17 @@ func (g *generator) walkAny(_ *openapi3.Schema) (ast.Type, error) {
}

func (g *generator) walkAllOf(schema *openapi3.Schema) (ast.Type, error) {
// TODO: Add discriminators
return g.walkDisjunctions(schema.AllOf)
return g.walkDisjunctions(schema.AllOf, "", nil)
K-Phoen marked this conversation as resolved.
Show resolved Hide resolved
}

func (g *generator) walkOneOf(schema *openapi3.Schema) (ast.Type, error) {
// TODO: Add discriminators
return g.walkDisjunctions(schema.OneOf)
discriminator, mapping := g.getDiscriminator(schema)
return g.walkDisjunctions(schema.OneOf, discriminator, mapping)
}

func (g *generator) walkAnyOf(schema *openapi3.Schema) (ast.Type, error) {
// TODO: Add discriminators
return g.walkDisjunctions(schema.AnyOf)
discriminator, mapping := g.getDiscriminator(schema)
return g.walkDisjunctions(schema.AnyOf, discriminator, mapping)
}

func (g *generator) walkEnum(schema *openapi3.Schema) (ast.Type, error) {
Expand All @@ -258,7 +251,7 @@ func (g *generator) walkEnum(schema *openapi3.Schema) (ast.Type, error) {
return ast.NewEnum(enums, ast.Default(schema.Default)), nil
}

func (g *generator) walkDisjunctions(schemaRefs []*openapi3.SchemaRef) (ast.Type, error) {
func (g *generator) walkDisjunctions(schemaRefs []*openapi3.SchemaRef, discriminator string, mapping map[string]string) (ast.Type, error) {
typeDefs := make([]ast.Type, 0, len(schemaRefs))
for _, schemaRef := range schemaRefs {
def, err := g.walkSchemaRef(schemaRef)
Expand All @@ -268,9 +261,17 @@ func (g *generator) walkDisjunctions(schemaRefs []*openapi3.SchemaRef) (ast.Type

typeDefs = append(typeDefs, def)
}
return ast.NewDisjunction(typeDefs), nil

return ast.NewDisjunction(typeDefs, ast.Discriminator(discriminator, mapping)), nil
}

func (g *generator) walkNot(_ *openapi3.Schema) (ast.Type, error) {
return ast.Type{}, errors.New("`not` aren't supported")
func (g *generator) getDiscriminator(schema *openapi3.Schema) (string, map[string]string) {
name := ""
mapping := make(map[string]string)
if schema.Discriminator != nil {
name = schema.Discriminator.PropertyName
mapping = schema.Discriminator.Mapping
}

return name, mapping
}
36 changes: 36 additions & 0 deletions internal/openapi/generator_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package openapi

import (
"fmt"
"testing"

"github.com/grafana/cog/internal/ast"
Expand Down Expand Up @@ -204,6 +205,38 @@ func TestRefs(t *testing.T) {
}
}

func TestDiscriminator(t *testing.T) {
f, err := GenerateAST(testFolder+"discriminator.json", Config{Package: "discriminator"})
require.NoError(t, err)

def := f.LocateObject("Discriminator")
assert.Equal(t, def.Type.Kind, ast.KindStruct)

structType := def.Type.AsStruct()

fmt.Printf("%v\n", structType)

testCases := []field{
{
name: "value",
kind: ast.KindDisjunction,
required: true,
discriminator: "discriminator",
},
{
name: "no-discriminator",
kind: ast.KindDisjunction,
discriminator: "",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
validateFields(t, structType, tc)
})
}
}

type field struct {
name string
kind ast.Kind
Expand All @@ -214,6 +247,7 @@ type field struct {
enumValues []ast.EnumValue
refType string
arrayTypeKind ast.Kind
discriminator string
}

func validateFields(t *testing.T, s ast.StructType, f field) {
Expand Down Expand Up @@ -242,5 +276,7 @@ func validateKind(t *testing.T, tp ast.Type, f field) {
case ast.KindArray:
assert.Equal(t, tp.AsArray().ValueType.Kind, f.arrayTypeKind)
validateKind(t, tp.AsArray().ValueType, f)
case ast.KindDisjunction:
assert.Equal(t, tp.AsDisjunction().Discriminator, f.discriminator)
}
}
76 changes: 76 additions & 0 deletions internal/openapi/testdata/discriminator.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"openapi": "3.0.0",
"info": {
"title": "discriminator",
"version": "0.0"
},
"paths": {},
"components": {
"schemas": {
"Discriminator": {
"type": "object",
"required": [
"value"
],
"properties": {
"value": {
"oneOf": [
{
"$ref": "#/components/schemas/Value1"
},
{
"$ref": "#/components/schemas/Value2"
},
{
"$ref": "#/components/schemas/Value3"
}
],
"discriminator": {
"propertyName": "discriminator"
}
},
"no-discriminator": {
"allOf": [
{
"$ref": "#/components/schemas/Value1"
},
{
"$ref": "#/components/schemas/Value2"
},
{
"$ref": "#/components/schemas/Value3"
}
]
}
}
},
"Value1": {
"type": "object",
"properties": {
"discriminator": {
"type": "string",
"default": "value1"
}
}
},
"Value2": {
"type": "object",
"properties": {
"discriminator": {
"type": "string",
"default": "value2"
}
}
},
"Value3": {
"type": "object",
"properties": {
"discriminator": {
"type": "string",
"default": "value3"
}
}
}
}
}
}
5 changes: 5 additions & 0 deletions internal/openapi/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,8 @@ func getArgs(v *float64, t string) []any {
}
return args
}

func getRefName(value string) string {
parts := strings.Split(value, "/")
return parts[len(parts)-1]
}
30 changes: 25 additions & 5 deletions schemas/openapi/core/dashboard/dashboard.json
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,8 @@
],
"properties": {
"type": {
"$ref": "#/components/schemas/MappingType"
"type": "string",
"default": "range"
},
"options": {
"type": "object",
Expand Down Expand Up @@ -700,7 +701,8 @@
],
"properties": {
"type": {
"$ref": "#/components/schemas/MappingType"
"type": "string",
"default": "regex"
},
"options": {
"type": "object",
Expand Down Expand Up @@ -851,7 +853,8 @@
],
"properties": {
"type": {
"$ref": "#/components/schemas/MappingType"
"type": "string",
"default": "special"
},
"options": {
"type": "object",
Expand Down Expand Up @@ -955,7 +958,8 @@
],
"properties": {
"type": {
"$ref": "#/components/schemas/MappingType"
"type": "string",
"default": "value"
},
"options": {
"type": "object",
Expand All @@ -966,7 +970,23 @@
}
},
"ValueMapping": {
"$ref": "#/components/schemas/ValueMap"
"oneOf": [
{
"$ref": "#/components/schemas/ValueMap"
},
{
"$ref": "#/components/schemas/RangeMap"
},
{
"$ref": "#/components/schemas/RegexMap"
},
{
"$ref": "#/components/schemas/SpecialValueMap"
}
],
"discriminator": {
"propertyName": "type"
}
},
"ValueMappingResult": {
"description": "TODO docs",
Expand Down