55 lines
1.4 KiB
Go
55 lines
1.4 KiB
Go
package apigen
|
|
|
|
import (
|
|
"fmt"
|
|
"git.yuntuo.hk/k2safe/go-omni/contract"
|
|
"git.yuntuo.hk/k2safe/go-omni/openapi"
|
|
"strings"
|
|
)
|
|
|
|
// Response roots deliberately allow named DTOs, []DTO, *DTO and null. Keeping
|
|
// these four shapes explicit makes nil/empty behavior uniform across encoders.
|
|
func responseShape(value string) (kind, name string) {
|
|
if value == "null" {
|
|
return "null", ""
|
|
}
|
|
if strings.HasPrefix(value, "[]") {
|
|
return "array", strings.TrimPrefix(value, "[]")
|
|
}
|
|
if strings.HasPrefix(value, "*") {
|
|
return "nullable", strings.TrimPrefix(value, "*")
|
|
}
|
|
return "object", value
|
|
}
|
|
func responseGoType(value string) string {
|
|
kind, name := responseShape(value)
|
|
if kind == "null" || value == "" {
|
|
return ""
|
|
}
|
|
if kind == "array" {
|
|
return "[]types." + name
|
|
}
|
|
return "*types." + name
|
|
}
|
|
func responseDataSchema(value string, bindings map[string]*contract.Binder) (*openapi.Schema, error) {
|
|
kind, name := responseShape(value)
|
|
if kind == "null" {
|
|
return &openapi.Schema{Type: "object", Nullable: true, Enum: []any{nil}}, nil
|
|
}
|
|
b, ok := bindings[name]
|
|
if !ok {
|
|
return nil, fmt.Errorf("unknown response DTO %q; use Name, []Name, *Name or null", name)
|
|
}
|
|
s, err := b.ResponseSchema()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch kind {
|
|
case "array":
|
|
return &openapi.Schema{Type: "array", Items: s}, nil
|
|
case "nullable":
|
|
s.Nullable = true
|
|
}
|
|
return s, nil
|
|
}
|