apigen

package
v1.101.2 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: AGPL-3.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const DateFormat = "2006-01-02T15:04:05.999Z"

DateFormat is the layout of dates passed into and out of the API.

View Source
const OutputRootDirEnvOverride = "STORJ_APIGEN_OUTPUT_TO_DIR"

OutputRootDirEnvOverride is the name of the environment variable that can be used to override the root directory used for the api.Write... functions.

Variables

This section is empty.

Functions

func LoadSetting added in v1.94.1

func LoadSetting[T any](key any, endpoint *FullEndpoint, defaultValue T) T

LoadSetting returns from endpoint.Settings the value assigned to key or returns defaultValue if the key doesn't exist.

It panics if key doesn't have a value of the type T.

func TypescriptTypeName added in v1.75.2

func TypescriptTypeName(t reflect.Type) string

TypescriptTypeName gets the corresponding TypeScript type for a provided reflect.Type. If the type is an anonymous struct, it returns an empty string.

Types

type API

type API struct {
	// Version is the corresponding version of the API.
	// It's concatenated to the BasePath, so assuming the base path is "/api" and the version is "v1"
	// the API paths will begin with `/api/v1`.
	// When empty, the version doesn't appear in the API paths. If it starts or ends with one or more
	// "/", they are stripped from the API endpoint paths.
	Version     string
	Description string
	// The package name to use for the Go generated code.
	// If omitted, the last segment of the PackagePath will be used as the package name.
	PackageName string
	// The path of the package that will use the generated Go code.
	// This is used to prevent the code from importing its own package.
	PackagePath string
	// BasePath is the  base path for the API endpoints. E.g. "/api".
	// It doesn't require to begin with "/". When empty, "/" is used.
	BasePath       string
	Auth           api.Auth
	EndpointGroups []*EndpointGroup

	// OutputRootDir is the root directory that functions like WriteGo, WriteTS, and WriteDocs will use.
	// If defined, the OutputRootDirEnvOverride environment variable will be used instead.
	OutputRootDir string
}

API represents specific API's configuration.

func (*API) Group

func (a *API) Group(name, prefix string) *EndpointGroup

Group adds new endpoints group to API. name must be `^([A-Z0-9]\w*)?$“ prefix must be `^\w*$`.

func (*API) MustWriteDocs added in v1.82.1

func (api *API) MustWriteDocs(path string)

MustWriteDocs generates API documentation and writes it to the specified file path. If an error occurs, it panics.

func (*API) MustWriteGo added in v1.55.1

func (a *API) MustWriteGo(path string)

MustWriteGo writes generated Go code into a file. If an error occurs, it panics.

func (*API) MustWriteTS added in v1.63.1

func (a *API) MustWriteTS(path string)

MustWriteTS writes generated TypeScript code into a file indicated by path. The generated code is an API client to run in the browser.

If an error occurs, it panics.

func (*API) MustWriteTSMock added in v1.91.2

func (a *API) MustWriteTSMock(path string)

MustWriteTSMock writes generated TypeScript code into a file indicated by path. The generated code is an API client mock to run in the browser.

If an error occurs, it panics.

type ClassField added in v1.95.1

type ClassField struct {
	Name     string
	Type     reflect.Type
	TypeName string
	Optional bool
	Nullable bool
}

ClassField is a description of a field to generate a string representation of a TypeScript class field.

func GetClassFieldsFromStruct added in v1.95.1

func GetClassFieldsFromStruct(t reflect.Type) []ClassField

GetClassFieldsFromStruct takes a struct type and returns the list of Class fields definition to create a TypeScript class based on t JSON representation.

It panics if t is not a struct, it has embedded fields that aren't structs, it has JSON tags names which aren't unique (considering that embedded ones are flatten into the class), a non-embedded field has no JSON tag, or a JSON tag is malformed.

func (*ClassField) String added in v1.95.1

func (c *ClassField) String() string

String returns the c string representation.

type Endpoint

type Endpoint struct {
	// Name is a free text used to name the endpoint for documentation purpose.
	// It cannot be empty.
	Name string
	// Description is a free text to describe the endpoint for documentation purpose.
	Description string
	// GoName is an identifier used by the Go generator to generate specific server side code for this
	// endpoint.
	//
	// It must start with an uppercase letter and fulfill the Go language specification for method
	// names (https://go.dev/ref/spec#MethodName).
	// It cannot be empty.
	GoName string
	// TypeScriptName is an identifier used by the TypeScript generator to generate specific client
	// code for this endpoint
	//
	// It must start with a lowercase letter and can only contains letters, digits, _, and $.
	// It cannot be empty.
	TypeScriptName string
	// Request is the type that defines the format of the request body.
	Request interface{}
	// Response is the type that defines the format of the response body.
	Response interface{}
	// QueryParams is the list of query parameters that the endpoint accepts.
	QueryParams []Param
	// PathParams is the list of path parameters that appear in the path associated with this
	// endpoint.
	PathParams []Param
	// ResponseMock is the data to use as a response for the generated mocks.
	// It must be of the same type than Response.
	// If a mock generator is called it must not be nil unless Response is nil.
	ResponseMock interface{}
	// Settings is the data to pass to the middleware handlers to adapt the generated
	// code to this endpoints.
	//
	// Not all the middlware handlers need extra data. Some of them use this data to disable it in
	// some endpoints.
	Settings map[any]any
}

Endpoint represents endpoint's configuration.

Passing an anonymous type to the fields that define the request or response will make the API generator to panic. Anonymous types aren't allowed such as named structs that have fields with direct or indirect of anonymous types, slices or arrays whose direct or indirect elements are of anonymous types.

func (*Endpoint) Validate added in v1.90.1

func (e *Endpoint) Validate() error

Validate validates the endpoint fields values are correct according to the documented constraints.

type EndpointGroup

type EndpointGroup struct {
	// Name is the group name.
	//
	// Go generator uses it as part of type, functions, interfaces names, and in code comments.
	// The casing is adjusted according where it's used.
	//
	// TypeScript generator uses it as part of types names for the API functionality of this group.
	// The casing is adjusted according where it's used.
	//
	// Document generator uses as it is.
	Name string
	// Prefix is a prefix used for
	//
	// Go generator uses it as part of variables names, error messages, and the URL base path for the group.
	// The casing is adjusted according where it's used, but for the URL base path, lowercase is used.
	//
	// TypeScript generator uses it for composing the URL base path (lowercase).
	//
	// Document generator uses as it is.
	Prefix string
	// Middleware is a list of additional processing of requests that apply to all the endpoints of this group.
	Middleware []Middleware
	// contains filtered or unexported fields
}

EndpointGroup represents endpoints group. You should always create a group using API.Group because it validates the field values to guarantee correct code generation.

func (*EndpointGroup) Delete added in v1.57.1

func (eg *EndpointGroup) Delete(path string, endpoint *Endpoint)

Delete adds new DELETE endpoint to endpoints group. It panics if path doesn't begin with '/'.

func (*EndpointGroup) Get

func (eg *EndpointGroup) Get(path string, endpoint *Endpoint)

Get adds new GET endpoint to endpoints group. It panics if path doesn't begin with '/'.

func (*EndpointGroup) Patch added in v1.54.1

func (eg *EndpointGroup) Patch(path string, endpoint *Endpoint)

Patch adds new PATCH endpoint to endpoints group. It panics if path doesn't begin with '/'.

func (*EndpointGroup) Post added in v1.55.1

func (eg *EndpointGroup) Post(path string, endpoint *Endpoint)

Post adds new POST endpoint to endpoints group. It panics if path doesn't begin with '/'.

func (*EndpointGroup) Put added in v1.53.1

func (eg *EndpointGroup) Put(path string, endpoint *Endpoint)

Put adds new PUT endpoint to endpoints group. It panics if path doesn't begin with '/'.

type FullEndpoint added in v1.94.1

type FullEndpoint struct {
	Endpoint
	Path   string
	Method string
}

FullEndpoint represents endpoint with path and method.

type Middleware added in v1.94.1

type Middleware interface {
	// Generate generates the code that the API generator adds to a handler endpoint before calling
	// the service.
	//
	// All the dependencies defined as struct fields of the implementation of this interface are
	// available as fields of the struct handler. The generated code is executed inside of the methods
	// of the struct handler, hence it has access to all its fields. The handler instance is available
	// through the variable name h. For example:
	//
	// type middlewareImpl struct {
	// 	 log  *zap.Logger // Import path: "go.uber.org/zap"
	//   auth api.Auth   // Import path: "storj.io/storj/private/api"
	// }
	//
	// The generated code can access to log and auth through h.log and h.auth.
	//
	// Each handler method where the code is executed has access to the following variables names:
	// ctx of type context.Context, w of type http.ResponseWriter, and r of type *http.Request.
	// Make sure to not declare variable with those names in the generated code unless that's wrapped
	// in a scope.
	Generate(api *API, group *EndpointGroup, ep *FullEndpoint) string
}

Middleware allows to generate custom code that's executed at the beginning of the handler.

The implementation must declare their dependencies through unexported struct fields which doesn't begin with underscore (_), except fields whose name is just underscore (the blank identifier). The API generator will add the import those dependencies and allow to pass them through the constructor parameters of the group handler implementation, except the fields named with the blank identifier that should be only used to import packages that the generated code needs.

The limitation of using fields with the blank identifier as its names is that those packages must at least to export a type, hence, it isn't possible to import packages that only export constants or variables.

Middleware implementation with the same struct field name and type will be handled as one parameter, so the dependency will be shared between them. If they have the same struct field name, but a different type, the API generator will panic. NOTE types are compared as [package].[type name], hence, package name collision are not handled and it will produce code that doesn't compile.

type Param added in v1.51.1

type Param struct {
	Name string
	Type reflect.Type
}

Param represents string interpretation of param's name and type.

func NewParam added in v1.51.1

func NewParam(name string, instance interface{}) Param

NewParam constructor which creates new Param entity by given name and type through instance.

instance can only be a unsigned integer (of any size), string, uuid.UUID or time.Time, otherwise it panics.

type StringBuilder added in v1.75.2

type StringBuilder struct{ strings.Builder }

StringBuilder is an extension of strings.Builder that allows for writing formatted lines.

func (*StringBuilder) Writelnf added in v1.75.2

func (s *StringBuilder) Writelnf(format string, a ...interface{})

Writelnf formats arguments according to a format specifier and appends the resulting string to the StringBuilder's buffer.

type Types added in v1.75.2

type Types struct {
	// contains filtered or unexported fields
}

Types handles generating definitions from types.

func NewTypes added in v1.75.2

func NewTypes() Types

NewTypes creates a new type definition generator.

func (*Types) All added in v1.75.2

func (types *Types) All() map[reflect.Type]string

All returns a map containing every top-level and their dependency types with their associated name.

func (*Types) GenerateTypescriptDefinitions added in v1.75.2

func (types *Types) GenerateTypescriptDefinitions() string

GenerateTypescriptDefinitions returns the TypeScript class definitions corresponding to the registered Go types.

func (*Types) Register added in v1.75.2

func (types *Types) Register(t reflect.Type)

Register registers a type for generation.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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