codegen

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 2, 2023 License: MIT Imports: 26 Imported by: 1

Documentation

Index

Constants

View Source
const (
	TagRegular = "regex"
)

Variables

View Source
var (
	Templates = []NodeTemplate{
		{
			Name:   "tag",
			Format: pkgf("%s_tag.go"),
		},
	}
	GraphTemplates = []GraphTemplate{
		{
			Name:   "interface",
			Format: "interface.go",
		},
		{
			Name:   "schema",
			Format: "model.go",
		},
		{
			Name:   "server",
			Format: "server/server.go",
		},
		{
			Name:   "validator",
			Format: "server/validator.go",
		},
	}
)

Functions

func AddPattern

func AddPattern(pattern string) (key string)

func GinReturnType

func GinReturnType(httpContent string) string

GinReturnType returns the which gin call for the incoming content type

func HasTag

func HasTag(src []string, tag string) bool

func IsBytes

func IsBytes(p code.Type) bool

IsBytes check if the response content type is bytes.

func IsSupportNegotiate

func IsSupportNegotiate(ress []string) bool

IsSupportNegotiate check if the response content type is support negotiate. if the response content type is not support negotiate, the response content type will be set to the first content type in the response use bytes.

func ModelMapToTypeInfo

func ModelMapToTypeInfo(model map[string]*ModelMap) (map[string]*code.TypeInfo, error)

func NewTemplate

func NewTemplate(name string) *helper.Template

NewTemplate creates an empty template with the standard codegen functions.

func OasUriToGinUri

func OasUriToGinUri(uri string) string

OasUriToGinUri converts a swagger style path URI with parameters to a Gin compatible path URI. We need to replace all Swagger parameters with ":param". Valid input parameters are:

{param}
{param*}
{.param}
{.param*}
{;param}
{;param*}
{?param}
{?param*}

func PrepareEnv

func PrepareEnv(c *Config) (undo func() error, err error)

PrepareEnv makes sure the generated directory (environment) is suitable for loading the `ent` package (avoid cyclic imports).

Types

type Config

type Config struct {
	OpenAPISchema string `json:"spec,omitempty"`
	Package       string `json:"package"`
	Target        string `json:"target,omitempty"`
	Header        string `json:"header,omitempty"`
	// Templates specifies a list of alternative templates to execute or
	// to override the default. If nil, the default template is used.
	//
	// Note that, additional templates are executed on the Graph object and
	// the execution output is stored in a file derived by the template name.
	Templates []*helper.Template
	// Hooks holds an optional list of Hooks to apply on the graph before/after the code-generation.
	Hooks []Hook

	Models  map[string]*ModelMap `json:"models,omitempty"`
	TypeMap map[string]*code.TypeInfo
	// Schemas is the list of all schemas reference in the spec.
	Schemas []*Schema
	// contains filtered or unexported fields
}

The Config holds the global codegen configuration to be shared between all generated nodes.

func (*Config) AddSchema

func (c *Config) AddSchema(ref string, schema *Schema)

func (*Config) AddTypeMap

func (c *Config) AddTypeMap(key string, t *code.TypeInfo)

func (Config) Imports

func (c Config) Imports() []string

type GenerateFunc

type GenerateFunc func(*Graph) error

The GenerateFunc type is an adapter to allow the use of ordinary function as Generator. If f is a function with the appropriate signature, GenerateFunc(f) is a Generator that calls f.

func (GenerateFunc) Generate

func (f GenerateFunc) Generate(g *Graph) error

type Generator

type Generator interface {
	// Generate generates the ent artifacts for the given graph.
	Generate(*Graph) error
}

type Graph

type Graph struct {
	*Config
	Nodes []*Tag

	Spec *openapi3.T
	// contains filtered or unexported fields
}

func NewGraph

func NewGraph(c *Config, schema *openapi3.T) (g *Graph, err error)

NewGraph creates a new Graph for the code generation from the given Spec definitions. It fails if one of the schemas is invalid.

func (*Graph) Gen

func (g *Graph) Gen() error

Gen generates the artifacts for the graph.

type GraphTemplate

type GraphTemplate struct {
	Name           string
	Format         string
	ExtendPatterns []string
	Skip           func(*Graph) bool
}

type Hook

type Hook func(Generator) Generator

Hook defines the "generate middleware". A function that gets a Generator and returns a Generator. For example:

hook := func(next gen.Generator) gen.Generator {
	return gen.GenerateFunc(func(g *Graph) error {
		fmt.Println("Graph:", g)
		return next.Generate(g)
	})
}

type ModelMap

type ModelMap struct {
	Model string `json:"model,omitempty"`
}

type NodeTemplate

type NodeTemplate struct {
	Name           string
	Format         func(*Tag) string
	ExtendPatterns []string
}

type Operation

type Operation struct {
	*Config
	Name             string
	Group            string // first tag name
	Method           string // GET, POST, DELETE, etc.
	Path             string
	Spec             *openapi3.Operation
	SpecPathItem     *openapi3.PathItem // navigation to pathItem
	Request          *Request
	Responses        []*Response
	ResponseOK       *Response
	ResponseNotFound *Response
	IgnoreInterface  bool
}

Operation is for operation of openapi3

func (*Operation) AddParameter

func (op *Operation) AddParameter(params ...*Parameter)

func (*Operation) GenRequest

func (op *Operation) GenRequest()

func (*Operation) GenResponse

func (op *Operation) GenResponse(codeStr string, spec *openapi3.ResponseRef) *Response

func (*Operation) GenResponses

func (op *Operation) GenResponses()

func (*Operation) GenSecurity

func (op *Operation) GenSecurity(ssSpec openapi3.SecuritySchemes)

func (*Operation) HasRequest

func (op *Operation) HasRequest() bool

func (*Operation) HasResponse

func (op *Operation) HasResponse() bool

func (*Operation) RequestName

func (op *Operation) RequestName() string

RequestName returns the name of the request struct.

func (*Operation) SimpleBody

func (op *Operation) SimpleBody() *Parameter

SimpleBody if request body is only one, use the parameter to body field

type Parameter

type Parameter struct {
	Name   string
	Schema *Schema
	Spec   *openapi3.Parameter
}

Parameter include parameter and requestBody

type Request

type Request struct {
	Parameters       []*Parameter
	BindUri          bool
	UriParameters    []*Parameter
	BindHeader       bool
	HeaderParameters []*Parameter
	BindCookie       bool
	CookieParameters []*Parameter
	BindBody         bool
	Body             []*Parameter
	BodyContentTypes []string
}

type Response

type Response struct {
	Name string
	// return content type when response is not empty
	ContentTypes []string
	// http status
	Status      int
	Schema      *Schema
	Spec        *openapi3.Response
	Description *string
}

Response is for response of openapi3

type Schema

type Schema struct {
	Spec       *openapi3.SchemaRef // The original OpenAPIv3 Schema.
	Name       string              // The name of the schema.
	Type       *code.TypeInfo      // The type of the schema.
	IsRef      bool
	HasRegular bool // if schema has a pattern setting
	Required   bool

	StructTags []string

	Properties map[string]*Schema
	IsInline   bool // if schema is inline , schema is embedded in another schema
	IsReplace  bool // if schema is replaced by model defined in config
	IsAlias    bool // if schema is alias of not go native type
	IsArray    bool
	// contains filtered or unexported fields
}

Schema is for schema of openapi3 a struct , the struct 's field all is Schema Properties are sort by name, because openapi3 use map to store properties,map is not ordered.

func (*Schema) AppendContentTypeStructTag

func (sch *Schema) AppendContentTypeStructTag(c *Config, tagName string, contentTypes []string)

AppendContentTypeStructTag parse content type and append to struct tags.if depends on Request or Response content type.

func (*Schema) CheckRequired

func (sch *Schema) CheckRequired()

CheckRequired checks if the schema is required and updates the schema type if needed

func (*Schema) CollectTags

func (sch *Schema) CollectTags()

CollectTags collects all struct tags from the schema and its children.

func (*Schema) CopyTo

func (sch *Schema) CopyTo(tg *Schema)

CopyTo copies the schema's base properties to the target schema

func (*Schema) GenSchemaType

func (sch *Schema) GenSchemaType(c *Config, name string, spec *openapi3.SchemaRef)

GenSchemaType generates the type of the parameter by SPEC. schema type from : the schema's sepc , additionalProperties, array items

func (*Schema) IsObjectArray

func (sch *Schema) IsObjectArray() bool

IsObjectArray returns true if the schema is an array of objects

func (Schema) StructTagsString

func (sch Schema) StructTagsString() string

type Tag

type Tag struct {
	*Config
	Name       string
	Operations []*Operation
	Spec       *openapi3.Tag
}

Tag is for tag of openapi3

func (*Tag) AddOperation

func (t *Tag) AddOperation(ops ...*Operation)

AddOperation adds an operation to the Tag.

func (*Tag) InterfaceName

func (t *Tag) InterfaceName() string

InterfaceName for Tag

func (*Tag) PackageDir

func (t *Tag) PackageDir() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL