openapi

package
v0.1.41 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ParameterInPath   = "path"
	ParameterInQuery  = "query"
	ParameterInHeader = "header"
)

Variables

View Source
var (
	ErrUnexpectedFormDataType       = errors.New("expected map[string]any for multipart/form-data")
	ErrUnexpectedFormURLEncodedType = errors.New("expected map[string]any for x-www-form-urlencoded")
	ErrGettingFileFromURL           = errors.New("error getting file from url")
)

Functions

func AssertJSONEqual

func AssertJSONEqual(t *testing.T, expected, actual any)

func CreateCURLBody

func CreateCURLBody(content any, contentType string) (string, error)

func CreateKinSchemaFromString

func CreateKinSchemaFromString(t *testing.T, jsonSrc string) *openapi3.Schema

func CreateOperationFromYAMLFile

func CreateOperationFromYAMLFile(t *testing.T, filePath string, target any)

func CreateSchemaFromString

func CreateSchemaFromString(t *testing.T, jsonSrc string) *types.Schema

func CreateSchemaFromYAMLFile

func CreateSchemaFromYAMLFile(t *testing.T, filePath string, target any)

func EncodeContent

func EncodeContent(content any, contentType string) ([]byte, error)

EncodeContent encodes content to the given content type. Since it is part of the JSON GeneratedRequest, we need to encode different content types to string before sending it.

func FixSchemaTypeTypos

func FixSchemaTypeTypos(typ string) string

FixSchemaTypeTypos fixes common typos in schema types.

func GenerateContentArray

func GenerateContentArray(schema *types.Schema, valueReplacer replacer.ValueReplacer, state *replacer.ReplaceState) any

GenerateContentArray generates content from the given schema with type `array`.

func GenerateContentFromFileProperties

func GenerateContentFromFileProperties(filePath, contentType string, valueReplacer replacer.ValueReplacer) []byte

func GenerateContentFromSchema

func GenerateContentFromSchema(schema *types.Schema, valueReplacer replacer.ValueReplacer, state *replacer.ReplaceState) any

GenerateContentFromSchema generates content from the given schema.

func GenerateContentObject

func GenerateContentObject(schema *types.Schema, valueReplacer replacer.ValueReplacer, state *replacer.ReplaceState) any

GenerateContentObject generates content from the given schema with type `object`.

func GenerateRequestHeaders

func GenerateRequestHeaders(parameters Parameters, valueReplacer replacer.ValueReplacer) map[string]any

GenerateRequestHeaders generates GeneratedRequest headers from the given parameters.

func GenerateResponseHeaders

func GenerateResponseHeaders(headers Headers, valueReplacer replacer.ValueReplacer) http.Header

GenerateResponseHeaders generates response headers from the given headers.

func GetJSONPair

func GetJSONPair(expected, actual any) (string, string)

func GetOpenAPITypeFromValue

func GetOpenAPITypeFromValue(value any) string

func NewSchemaFromKin

func NewSchemaFromKin(schema *openapi3.Schema, parseConfig *config.ParseConfig) *types.Schema

NewSchemaFromKin creates a new Scheme from a Kin schema

func TransformHTTPCode

func TransformHTTPCode(httpCode string) int

TransformHTTPCode transforms HTTP code from the OpenAPI spec to the real HTTP code.

Types

type AuthLocation

type AuthLocation string
const (
	AuthLocationHeader AuthLocation = "header"
	AuthLocationQuery  AuthLocation = "query"
)

type AuthScheme

type AuthScheme string
const (
	AuthSchemeBearer AuthScheme = "bearer"
	AuthSchemeBasic  AuthScheme = "basic"
)

type AuthType

type AuthType string
const (
	AuthTypeHTTP   AuthType = "http"
	AuthTypeApiKey AuthType = "apiKey"
)

type CacheOperationAdapter

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

CacheOperationAdapter is an adapter that caches the result of the wrapped KinOperation. Implements KinOperation interface.

func (*CacheOperationAdapter) GetRequest

func (a *CacheOperationAdapter) GetRequest(securityComponents SecurityComponents) *Request

func (*CacheOperationAdapter) GetResponse

func (a *CacheOperationAdapter) GetResponse() *Response

GetResponse returns the response for the KinOperation.

func (*CacheOperationAdapter) ID

func (a *CacheOperationAdapter) ID() string

ID returns the ID of the KinOperation.

func (*CacheOperationAdapter) Unwrap

func (a *CacheOperationAdapter) Unwrap() Operation

func (*CacheOperationAdapter) WithParseConfig

func (a *CacheOperationAdapter) WithParseConfig(parseConfig *config.ParseConfig) Operation

WithParseConfig sets the ParseConfig for the KinOperation.

type CacheStorage

type CacheStorage interface {
	Set(key string, value any) error
	Get(key string) (any, bool)
}

CacheStorage is an interface that describes a cache storage.

type ContentExample

type ContentExample struct {
	CURL string `json:"curl,omitempty"`
}

ContentExample is a struct that represents a generated cURL example.

type Document

type Document interface {
	GetVersion() string
	GetResources() map[string][]string
	GetSecurity() SecurityComponents
	FindOperation(options *OperationDescription) Operation
}

Document is an interface that represents an OpenAPI document needed for content generation. It is implemented by the LibV2Document and LibV3Document types.

type FileProperties

type FileProperties struct {
	ServiceName string
	IsOpenAPI   bool
	Method      string
	Prefix      string
	Resource    string
	FilePath    string
	FileName    string
	Extension   string
	ContentType string
	Spec        Document `json:"-"`
}

FileProperties contains inferred properties of a file that is being loaded from service directory.

ServiceName is the name of the service that the file belongs to. It represents the first directory in the file path.

IsOpenAPI indicates whether the file is an OpenAPI specification. Method is the HTTP method of the resource, which this file describes. Prefix is the path prefix of the resource, which this file describes. This is service name with a leading slash.

Resource is the path of the resource, which this file describes without prefix. FilePath is the full path to the file. FileName is the name of the file with the extension. Extension is the extension of the file, with the leading dot. ContentType is the MIME type of the file. Spec is the OpenAPI specification of the file if the file iis an OpenAPI specification.

func GetPropertiesFromFilePath

func GetPropertiesFromFilePath(filePath string, appCfg *config.AppConfig) (*FileProperties, error)

GetPropertiesFromFilePath gets properties of a file from its path.

func (*FileProperties) IsEqual

func (f *FileProperties) IsEqual(other *FileProperties) bool

IsEqual compares two FileProperties structs. Spec is not compared.

type GenerateRequestOptions

type GenerateRequestOptions struct {
	PathPrefix string
	Path       string
	Method     string
	Operation  Operation
}

type GeneratedRequest

type GeneratedRequest struct {
	Headers       map[string]any  `json:"headers,omitempty"`
	Method        string          `json:"method,omitempty"`
	Path          string          `json:"path,omitempty"`
	Query         string          `json:"query,omitempty"`
	Body          string          `json:"body,omitempty"`
	ContentType   string          `json:"contentType,omitempty"`
	ContentSchema *types.Schema   `json:"contentSchema,omitempty"`
	Examples      *ContentExample `json:"examples,omitempty"`

	// internal fields. needed for some validation provider.
	Request *http.Request `json:"-"`
}

GeneratedRequest is a struct that represents a generated GeneratedRequest to be used when building real endpoint GeneratedRequest.

func NewRequestFromFixedResource

func NewRequestFromFixedResource(path, method, contentType string, valueReplacer replacer.ValueReplacer) *GeneratedRequest

func NewRequestFromOperation

func NewRequestFromOperation(
	options *GenerateRequestOptions,
	securityComponents SecurityComponents,
	valueReplacer replacer.ValueReplacer) *GeneratedRequest

NewRequestFromOperation creates a new GeneratedRequest. It is used to pre-generate payloads from the UI or provide service to generate such. It's not part of OpenAPI endpoint handler.

type GeneratedResponse

type GeneratedResponse struct {
	Headers     http.Header `json:"headers,omitempty"`
	Content     []byte      `json:"content,omitempty"`
	ContentType string      `json:"contentType,omitempty"`
	StatusCode  int         `json:"statusCode,omitempty"`

	// internal fields. needed for some validation provider.
	Operation Operation     `json:"-"`
	Request   *http.Request `json:"-"`
}

GeneratedResponse is a struct that represents a generated response to be used when comparing real endpoint response.

func NewResponseFromFixedResource

func NewResponseFromFixedResource(filePath, contentType string, valueReplacer replacer.ValueReplacer) *GeneratedResponse

func NewResponseFromOperation

func NewResponseFromOperation(req *http.Request, operation Operation, valueReplacer replacer.ValueReplacer) *GeneratedResponse

NewResponseFromOperation creates generated response. It used to pre-generate payloads from the UI or provide service to generate such.

type Headers

type Headers map[string]*Parameter

Headers is a map of Parameter.

type KinDocument

type KinDocument struct {
	*openapi3.T
}

KinDocument is a wrapper around openapi3.T Implements Document interface

func NewDocumentFromFile

func NewDocumentFromFile(filePath string) (*KinDocument, error)

NewDocumentFromFile creates a new Document from a file path

func (*KinDocument) FindOperation

func (d *KinDocument) FindOperation(options *OperationDescription) Operation

FindOperation finds an operation by resource and method.

func (*KinDocument) GetResources

func (d *KinDocument) GetResources() map[string][]string

GetResources returns a map of resource names and their methods.

func (*KinDocument) GetSecurity

func (d *KinDocument) GetSecurity() SecurityComponents

func (*KinDocument) GetVersion

func (d *KinDocument) GetVersion() string

GetVersion returns the version of the document

type KinOperation

type KinOperation struct {
	*openapi3.Operation
	// contains filtered or unexported fields
}

KinOperation is a wrapper around openapi3.Operation

func (*KinOperation) GetRequest

func (op *KinOperation) GetRequest(securityComponents SecurityComponents) *Request

func (*KinOperation) GetResponse

func (op *KinOperation) GetResponse() *Response

GetResponse returns the operation response

func (*KinOperation) ID

func (op *KinOperation) ID() string

ID returns the operation ID

func (*KinOperation) Unwrap

func (op *KinOperation) Unwrap() Operation

func (*KinOperation) WithParseConfig

func (op *KinOperation) WithParseConfig(config *config.ParseConfig) Operation

WithParseConfig sets the parse config for this operation

type KinValidator

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

func NewValidator

func NewValidator(_ Document) *KinValidator

NewValidator creates a new KinValidator from kin-openapi document.

func (*KinValidator) ValidateRequest

func (v *KinValidator) ValidateRequest(req *GeneratedRequest) []error

ValidateRequest validates GeneratedRequest against a schema.

func (*KinValidator) ValidateResponse

func (v *KinValidator) ValidateResponse(res *GeneratedResponse) []error

ValidateResponse validates a response against an KinOperation. GeneratedResponse must contain non-empty headers or it'll fail validation.

type MemoryStorage

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

MemoryStorage is a cache storage that stores data in memory.

func NewMemoryStorage

func NewMemoryStorage() *MemoryStorage

NewMemoryStorage creates a new MemoryStorage instance.

func (*MemoryStorage) Get

func (s *MemoryStorage) Get(key string) (any, bool)

Get returns the value for the given key.

func (*MemoryStorage) Set

func (s *MemoryStorage) Set(key string, value any) error

Set sets the value for the given key.

type Operation

type Operation interface {
	ID() string
	Unwrap() Operation
	GetRequest(securityComponents SecurityComponents) *Request
	GetResponse() *Response
	WithParseConfig(*config.ParseConfig) Operation
}

Operation is an interface that represents an OpenAPI operation needed for content generation.

func NewCacheOperationAdapter

func NewCacheOperationAdapter(service string, operation Operation, storage CacheStorage) Operation

NewCacheOperationAdapter creates a new CacheOperationAdapter instance.

type OperationDescription

type OperationDescription struct {
	Service  string
	Resource string
	Method   string
}

OperationDescription is a struct that used to find an operation in an OpenAPI document.

type Parameter

type Parameter struct {
	Name     string        `json:"name,omitempty" yaml:"name,omitempty"`
	In       string        `json:"in,omitempty" yaml:"in,omitempty"`
	Required bool          `json:"required,omitempty" yaml:"required,omitempty"`
	Schema   *types.Schema `json:"schema,omitempty" yaml:"schema,omitempty"`
	Example  any           `json:"example,omitempty" yaml:"example,omitempty"`
}

Parameter is a struct that represents an OpenAPI parameter.

type Parameters

type Parameters []*Parameter

Parameters is a slice of Parameter.

type Request

type Request struct {
	Parameters Parameters
	Body       *RequestBody
}

type RequestBody

type RequestBody struct {
	Schema *types.Schema
	Type   string
}

type Response

type Response struct {
	Headers     Headers
	Content     *types.Schema
	ContentType string
	StatusCode  int
}

Response is a struct that represents an OpenAPI response.

type SchemaWithContentType

type SchemaWithContentType struct {
	Schema      *types.Schema
	ContentType string
}

SchemaWithContentType is a schema with a content type. It is used to cache the result of getRequestBody and wrap 2 values together.

type SecurityComponent

type SecurityComponent struct {
	Type   AuthType
	Scheme AuthScheme
	In     AuthLocation
	Name   string
}

type SecurityComponents

type SecurityComponents map[string]*SecurityComponent

type UploadedFile

type UploadedFile struct {
	Content   []byte
	Filename  string
	Extension string
	Size      int64
}

UploadedFile represents an uploaded file. Content is the content of the file. Filename is the name of the file. Extension is the extension of the file with the leading dot. Size is the size of the file in bytes.

func GetRequestFile

func GetRequestFile(r *http.Request, fieldName string) (*UploadedFile, error)

GetRequestFile gets an uploaded file from a GeneratedRequest.

Jump to

Keyboard shortcuts

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