gf/protocol/goai/goai_shemaref.go

87 lines
2.1 KiB
Go
Raw Normal View History

2021-10-02 18:54:06 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2021-10-02 14:52:28 +08:00
package goai
import (
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/util/gconv"
2021-10-02 14:52:28 +08:00
"reflect"
)
type SchemaRefs []SchemaRef
type SchemaRef struct {
Ref string
Value *Schema
}
2021-10-02 18:54:06 +08:00
func (oai *OpenApiV3) newSchemaRefWithGolangType(golangType reflect.Type, tagMap map[string]string) (*SchemaRef, error) {
2021-10-02 14:52:28 +08:00
var (
oaiType = oai.golangTypeToOAIType(golangType)
2021-10-02 15:07:47 +08:00
oaiFormat = oai.golangTypeToOAIFormat(golangType)
2021-10-02 18:54:06 +08:00
schemaRef = &SchemaRef{}
2021-10-02 14:52:28 +08:00
schema = &Schema{
2021-10-02 15:07:47 +08:00
Type: oaiType,
Format: oaiFormat,
2021-10-02 14:52:28 +08:00
}
)
if len(tagMap) > 0 {
2021-10-02 18:54:06 +08:00
if err := gconv.Struct(tagMap, schema); err != nil {
return nil, gerror.WrapCode(gcode.CodeInternalError, err, `mapping struct tags to Schema failed`)
2021-10-02 14:52:28 +08:00
}
}
schemaRef.Value = schema
switch oaiType {
case
TypeNumber,
TypeString,
TypeBoolean:
// Nothing to do.
case
TypeArray:
2021-10-02 18:54:06 +08:00
subSchemaRef, err := oai.newSchemaRefWithGolangType(golangType.Elem(), nil)
if err != nil {
return nil, err
}
schema.Items = subSchemaRef
2021-10-02 14:52:28 +08:00
case
TypeObject:
var (
2021-10-06 21:51:21 +08:00
structTypeName = golangTypeToSchemaName(golangType)
2021-10-02 14:52:28 +08:00
)
// Specially for map type.
if golangType.Kind() == reflect.Map {
2021-10-02 18:54:06 +08:00
subSchemaRef, err := oai.newSchemaRefWithGolangType(golangType.Elem(), nil)
if err != nil {
return nil, err
}
schema.AdditionalProperties = subSchemaRef
return schemaRef, nil
2021-10-02 14:52:28 +08:00
}
// Normal struct object.
if _, ok := oai.Components.Schemas[structTypeName]; !ok {
2021-10-13 22:28:49 +08:00
if err := oai.addSchema(reflect.New(golangType).Elem().Interface()); err != nil {
2021-10-02 18:54:06 +08:00
return nil, err
}
2021-10-02 14:52:28 +08:00
}
schemaRef.Ref = structTypeName
schemaRef.Value = nil
}
2021-10-02 18:54:06 +08:00
return schemaRef, nil
2021-10-02 14:52:28 +08:00
}
func (r SchemaRef) MarshalJSON() ([]byte, error) {
if r.Ref != "" {
2021-10-02 18:54:06 +08:00
return formatRefToBytes(r.Ref), nil
2021-10-02 14:52:28 +08:00
}
return json.Marshal(r.Value)
}