github.com/circl-dev/go-swagger@v0.31.0/generator/discriminators.go (about)

     1  package generator
     2  
     3  import (
     4  	"github.com/circl-dev/analysis"
     5  	"github.com/circl-dev/spec"
     6  	"github.com/go-openapi/swag"
     7  )
     8  
     9  type discInfo struct {
    10  	Discriminators map[string]discor
    11  	Discriminated  map[string]discee
    12  }
    13  
    14  type discor struct {
    15  	FieldName string   `json:"fieldName"`
    16  	GoType    string   `json:"goType"`
    17  	JSONName  string   `json:"jsonName"`
    18  	Children  []discee `json:"children"`
    19  }
    20  
    21  type discee struct {
    22  	FieldName  string   `json:"fieldName"`
    23  	FieldValue string   `json:"fieldValue"`
    24  	GoType     string   `json:"goType"`
    25  	JSONName   string   `json:"jsonName"`
    26  	Ref        spec.Ref `json:"ref"`
    27  	ParentRef  spec.Ref `json:"parentRef"`
    28  }
    29  
    30  func discriminatorInfo(doc *analysis.Spec) *discInfo {
    31  	baseTypes := make(map[string]discor)
    32  	for _, sch := range doc.AllDefinitions() {
    33  		if sch.Schema.Discriminator != "" {
    34  			tpe, _ := sch.Schema.Extensions.GetString(xGoName)
    35  			if tpe == "" {
    36  				tpe = swag.ToGoName(sch.Name)
    37  			}
    38  			baseTypes[sch.Ref.String()] = discor{
    39  				FieldName: sch.Schema.Discriminator,
    40  				GoType:    tpe,
    41  				JSONName:  sch.Name,
    42  			}
    43  		}
    44  	}
    45  
    46  	subTypes := make(map[string]discee)
    47  	for _, sch := range doc.SchemasWithAllOf() {
    48  		for _, ao := range sch.Schema.AllOf {
    49  			if ao.Ref.String() != "" {
    50  				if bt, ok := baseTypes[ao.Ref.String()]; ok {
    51  					name, _ := sch.Schema.Extensions.GetString(xClass)
    52  					if name == "" {
    53  						name = sch.Name
    54  					}
    55  					tpe, _ := sch.Schema.Extensions.GetString(xGoName)
    56  					if tpe == "" {
    57  						tpe = swag.ToGoName(sch.Name)
    58  					}
    59  					dce := discee{
    60  						FieldName:  bt.FieldName,
    61  						FieldValue: name,
    62  						Ref:        sch.Ref,
    63  						ParentRef:  ao.Ref,
    64  						JSONName:   sch.Name,
    65  						GoType:     tpe,
    66  					}
    67  					subTypes[sch.Ref.String()] = dce
    68  					bt.Children = append(bt.Children, dce)
    69  					baseTypes[ao.Ref.String()] = bt
    70  				}
    71  			}
    72  		}
    73  	}
    74  	return &discInfo{Discriminators: baseTypes, Discriminated: subTypes}
    75  }