internal

package
v0.1.37 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2025 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// RootServiceName is the name and location in the service directory of the service without a name.
	RootServiceName = "root"

	// RootOpenAPIName is the name and location of the OpenAPI service without a name.
	RootOpenAPIName = "openapi"
)
View Source
const (
	TypeArray   = "array"
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeObject  = "object"
	TypeString  = "string"
)
View Source
const (
	ParameterInPath   = "path"
	ParameterInQuery  = "query"
	ParameterInHeader = "header"
)
View Source
const (
	NULL = "__null__"
)

NULL is used to force resolve to nil

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")
)
View Source
var (
	ErrGettingFileFromURL = errors.New("error getting file from url")
)
View Source
var Fakes = GetFakes()

Fakes is a map of registered fake functions.

View Source
var PlaceholderRegex = regexp.MustCompile(`\{[^\}]*\}`)

Replacers is a list of replacers that are used to replace values in schemas and contents in the specified order.

View Source
var (
	TestDataPath = filepath.Join(filepath.Dir(b), "..", "testdata")
)

Functions

func AppendSliceFirstNonEmpty

func AppendSliceFirstNonEmpty[T comparable](data []T, value ...T) []T

AppendSliceFirstNonEmpty appends the first non-empty value to the given slice.

func ApplySchemaConstraints added in v0.1.30

func ApplySchemaConstraints(openAPISchema any, res any) any

ApplySchemaConstraints applies schema constraints to the value. It converts the input value to match the corresponding OpenAPI type specified in the schema.

func Base64Encode added in v0.1.29

func Base64Encode(input string) string

func CastToSchemaFormat added in v0.1.30

func CastToSchemaFormat(ctx *ReplaceContext, value any) any

CastToSchemaFormat casts the value to the schema format if possible. If the schema format is not specified, the value is returned as-is.

func CleanupServiceFileStructure added in v0.1.30

func CleanupServiceFileStructure(servicePath string) error

CleanupServiceFileStructure removes empty directories from the service directory.

func CollectContexts added in v0.1.30

func CollectContexts(names []map[string]string, fileCollections map[string]map[string]any,
	initial map[string]any) []map[string]any

CollectContexts collects contexts from the given list of context names, file collections and initial context.

func CompilePlugin added in v0.1.30

func CompilePlugin(dir string) (*plugin.Plugin, error)

CompilePlugin compiles user-provided Go code into a shared library. In debugging mode, add DEBUG_BUILD=true to the environment variables.

func CopyDirectory added in v0.1.30

func CopyDirectory(src, dest string) error

CopyDirectory copies a directory recursively.

func CopyFile added in v0.1.30

func CopyFile(srcPath, destPath string) error

CopyFile copies a file from srcPath to destPath. If the destination directory doesn't exist, it will be created.

func CopyNestedMap

func CopyNestedMap(source map[string]map[string]any) map[string]map[string]any

CopyNestedMap returns a copy of the given map with all nested maps copied as well.

func CreateCURLBody added in v0.1.30

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

func EncodeContent added in v0.1.30

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 ExtractPlaceholders

func ExtractPlaceholders(input string) []string

ExtractPlaceholders extracts all placeholders including curly brackets from a pattern.

func ExtractZip added in v0.1.30

func ExtractZip(zipReader *zip.Reader, targetDir string, onlyPrefixes []string) error

ExtractZip extracts a zip archive to a target directory. onlyPrefixes is a list of prefixes that are allowed to be extracted.

func FixSchemaTypeTypos added in v0.1.30

func FixSchemaTypeTypos(typ string) string

FixSchemaTypeTypos fixes common typos in schema types.

func GenerateContentArray added in v0.1.30

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

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

func GenerateContentFromFileProperties added in v0.1.30

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

func GenerateContentFromSchema added in v0.1.30

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

GenerateContentFromSchema generates content from the given schema.

func GenerateContentObject added in v0.1.30

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

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

func GenerateRequestHeaders added in v0.1.30

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

GenerateRequestHeaders generates GeneratedRequest headers from the given parameters.

func GenerateResponseHeaders added in v0.1.30

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

GenerateResponseHeaders generates response headers from the given headers.

func GetFakeFuncFactoryWithString added in v0.1.30

func GetFakeFuncFactoryWithString() map[string]FakeFuncFactoryWithString

GetFakeFuncFactoryWithString returns a map of utility fake functions.

func GetFakes added in v0.1.30

func GetFakes() map[string]FakeFunc

GetFakes returns a map of fake functions from underlying fake library by gathering all exported methods from the faker.Faker struct into map. The keys are the snake_cased dot-separated method names, which reflect the location of the function: For example: person.first_name will return a fake first name from the Person struct.

func GetFileContentsFromURL added in v0.1.30

func GetFileContentsFromURL(client *http.Client, url string) ([]byte, string, error)

func GetFileHash added in v0.1.30

func GetFileHash(file io.Reader) string

GetFileHash gets the SHA256 hash of a file.

func GetOpenAPITypeFromValue added in v0.1.30

func GetOpenAPITypeFromValue(value any) string

func GetRandomKeyFromMap

func GetRandomKeyFromMap[T any](m map[string]T) string

GetRandomKeyFromMap returns a random key from the given map.

func GetRandomSliceValue

func GetRandomSliceValue[T any](slice []T) T

GetRandomSliceValue returns a random value from the given slice.

func GetSliceMaxRepetitionNumber

func GetSliceMaxRepetitionNumber[T comparable](values []T) int

GetSliceMaxRepetitionNumber returns the maximum number of non-unique values in the given slice.

func GetSortedMapKeys

func GetSortedMapKeys[T any](content map[string]T) []string

GetSortedMapKeys returns the keys of the given map sorted alphabetically.

func GetValueByDottedPath

func GetValueByDottedPath(data map[string]any, path string) any

GetValueByDottedPath returns the value of the given path in the given map. If the path does not exist, nil is returned. e.g. GetValueByDottedPath(map[string]any{"a": map[string]any{"b": 1}}, "a.b") returns 1

func HasCorrectSchemaValue added in v0.1.30

func HasCorrectSchemaValue(ctx *ReplaceContext, value any) bool

HasCorrectSchemaValue checks if the value is of the correct type and format.

func IsCorrectlyReplacedType added in v0.1.30

func IsCorrectlyReplacedType(value any, neededType string) bool

IsCorrectlyReplacedType checks if the given value is of the correct schema type.

func IsEmptyDir added in v0.1.30

func IsEmptyDir(path string) bool

IsEmptyDir checks if a directory is empty.

func IsInteger

func IsInteger(value any) bool

IsInteger checks if the value is an integer

func IsJsonType added in v0.1.30

func IsJsonType(content []byte) bool

IsJsonType checks if the content is a valid JSON document.

func IsMap

func IsMap(i any) bool

IsMap checks if the value is a map

func IsMatchSchemaReadWriteToState added in v0.1.30

func IsMatchSchemaReadWriteToState(schema *Schema, state *ReplaceState) bool

IsMatchSchemaReadWriteToState checks if the given schema is read-write match. ReadOnly - A property that is only available in a response. WriteOnly - A property that is only available in a request.

func IsNumber

func IsNumber(value any) bool

IsNumber checks if the value is a number: integer or float

func IsSliceUnique

func IsSliceUnique[T comparable](path []T) bool

IsSliceUnique returns true if all values in the given slice are unique.

func IsValidHTTPVerb

func IsValidHTTPVerb(verb string) bool

IsValidHTTPVerb checks if the given HTTP verb is valid.

func IsValidURLResource

func IsValidURLResource(urlPattern string) bool

IsValidURLResource checks if the given URL resource pattern is valid: placeholders contain only alphanumeric characters, underscores, and hyphens

func IsYamlType added in v0.1.30

func IsYamlType(content []byte) bool

IsYamlType checks if the content is a valid YAML document.

func MapToURLEncodedForm

func MapToURLEncodedForm(data map[string]any) string

MapToURLEncodedForm converts a map to a URL encoded form. e.g. {"a": {"b": 1}} becomes "a[b]=1"

func MaybeRegexPattern

func MaybeRegexPattern(input string) bool

MaybeRegexPattern checks if the input string contains any special characters. This is a simple good-enough check to see if the context key is a regex pattern.

func RemovePointer

func RemovePointer[T bool | float64 | int64 | uint64](value *T) T

RemovePointer removes pointer from the boolean or numeric value

func ReplaceFromContext added in v0.1.30

func ReplaceFromContext(ctx *ReplaceContext) any

ReplaceFromContext is a replacer that replaces values from the context.

func ReplaceFromSchemaExample added in v0.1.30

func ReplaceFromSchemaExample(ctx *ReplaceContext) any

ReplaceFromSchemaExample is a replacer that replaces values from the schema example.

func ReplaceFromSchemaFallback added in v0.1.30

func ReplaceFromSchemaFallback(ctx *ReplaceContext) any

ReplaceFromSchemaFallback is the last resort to get a value from the schema.

func ReplaceFromSchemaFormat added in v0.1.30

func ReplaceFromSchemaFormat(ctx *ReplaceContext) any

ReplaceFromSchemaFormat is a replacer that replaces values from the schema format.

func ReplaceFromSchemaPrimitive added in v0.1.30

func ReplaceFromSchemaPrimitive(ctx *ReplaceContext) any

ReplaceFromSchemaPrimitive is a replacer that replaces values from the schema primitive.

func ReplaceInHeaders added in v0.1.30

func ReplaceInHeaders(ctx *ReplaceContext) any

ReplaceInHeaders is a replacer that replaces values only in headers.

func ReplaceInPath added in v0.1.30

func ReplaceInPath(ctx *ReplaceContext) any

ReplaceInPath is a replacer that replaces values only in path parameters.

func ReplaceValueWithContext added in v0.1.30

func ReplaceValueWithContext(path []string, contextData any) interface{}

ReplaceValueWithContext is a replacer that replaces values from the context.

func SaveFile added in v0.1.30

func SaveFile(filePath string, data []byte) error

SaveFile saves a file to the specified path. If the destination directory doesn't exist, it will be created.

func SetValueByDottedPath

func SetValueByDottedPath(data map[string]any, path string, value any)

SetValueByDottedPath sets the value of the given path in the given map. If the path does not exist, it is created. e.g. SetValueByDottedPath(map[string]any{"a": map[string]any{"b": 1}}, "a.b", 2) sets the value of "a.b" to 2 ! This function modifies the given map.

func SliceContains

func SliceContains[T comparable](slice []T, value T) bool

SliceContains returns true if the given slice contains the given value.

func SliceDeleteAtIndex

func SliceDeleteAtIndex[T any](slice []T, index int) []T

SliceDeleteAtIndex deletes an element from a slice at the given index and preserves the order of the slice.

func SliceUnique

func SliceUnique[T comparable](slice []T) []T

SliceUnique returns a new slice with unique values from the given slice.

func ToFloat64

func ToFloat64(value any) (float64, error)

ToFloat64 converts underlying value to float64 if it can be represented as float64

func ToInt32

func ToInt32(value any) (int32, bool)

ToInt32 converts underlying value to int32 if it can be represented as int32

func ToInt64

func ToInt64(value any) (int64, bool)

ToInt64 converts underlying value to int64 if it can be represented as int64

func ToSnakeCase

func ToSnakeCase(input string) string

ToSnakeCase converts a string to snake_case case

func ToString

func ToString(value any) string

func TransformHTTPCode added in v0.1.30

func TransformHTTPCode(httpCode string) int

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

func ValidateStringWithPattern

func ValidateStringWithPattern(input string, pattern string) bool

ValidateStringWithPattern checks if the input string matches the given pattern.

Types

type Any added in v0.1.30

type Any interface {
	string | int | bool | float64 | any
}

Any is a type that can be used to represent any type in generics.

type AppConfig added in v0.1.30

type AppConfig struct {
	Port                int           `json:"port" yaml:"port" koanf:"port"`
	HomeURL             string        `json:"homeUrl" yaml:"homeURL" koanf:"homeUrl"`
	ServiceURL          string        `json:"serviceUrl" yaml:"serviceURL" koanf:"serviceUrl"`
	SettingsURL         string        `json:"settingsUrl" yaml:"settingsURL" koanf:"settingsUrl"`
	ContextURL          string        `json:"contextUrl" yaml:"contextUrl" koanf:"contextUrl"`
	ContextAreaPrefix   string        `json:"contextAreaPrefix" yaml:"contextAreaPrefix" koanf:"contextAreaPrefix"`
	DisableUI           bool          `json:"disableUI" yaml:"disableUI" koanf:"disableUI"`
	DisableSwaggerUI    bool          `json:"disableSwaggerUI" yaml:"disableSwaggerUI" koanf:"disableSwaggerUI"`
	Paths               *Paths        `json:"-" koanf:"-"`
	CreateFileStructure bool          `koanf:"createFileStructure" json:"createFileStructure" yaml:"createFileStructure"`
	Editor              *EditorConfig `koanf:"editor" json:"editor" yaml:"editor"`
}

AppConfig is the app configuration. Port is the port number to listen on. HomeURL is the URL for the UI home page. ServiceURL is the URL for the service and resources endpoints in the UI. SettingsURL is the URL for the settings endpoint in the UI. ContextURL is the URL for the context endpoint in the UI. ContextAreaPrefix sets sub-contexts for replacements in path, header or any other supported place.

for example: in-path:

user_id: "fake:ids.int8"

DisableUI is a flag whether to disable the UI. DisableSpec is a flag whether to disable the Swagger UI. Paths is the paths to various resource directories. CreateFileStructure is a flag whether to create the initial resources file structure: contexts, services, etc. It will also copy sample files from the samples directory into services. Default: true

func NewDefaultAppConfig added in v0.1.30

func NewDefaultAppConfig(baseDir string) *AppConfig

NewDefaultAppConfig creates a new default app config in case the config file is missing, not found or any other error.

func (*AppConfig) IsValidPrefix added in v0.1.30

func (a *AppConfig) IsValidPrefix(prefix string) bool

IsValidPrefix returns true if the prefix is not a reserved URL.

type AuthLocation added in v0.1.30

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

type AuthScheme added in v0.1.30

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

type AuthType added in v0.1.30

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

type BoolValue added in v0.1.30

type BoolValue bool

func (BoolValue) Get added in v0.1.30

func (b BoolValue) Get() any

type CacheOperationAdapter added in v0.1.30

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 added in v0.1.30

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

func (*CacheOperationAdapter) GetResponse added in v0.1.30

func (a *CacheOperationAdapter) GetResponse() *Response

GetResponse returns the response for the KinOperation.

func (*CacheOperationAdapter) ID added in v0.1.30

func (a *CacheOperationAdapter) ID() string

ID returns the ID of the KinOperation.

func (*CacheOperationAdapter) Unwrap added in v0.1.30

func (a *CacheOperationAdapter) Unwrap() Operation

func (*CacheOperationAdapter) WithParseConfig added in v0.1.30

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

WithParseConfig sets the ParseConfig for the KinOperation.

type CacheStorage added in v0.1.30

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

CacheStorage is an interface that describes a cache storage.

type Config added in v0.1.30

type Config struct {
	App      *AppConfig                `koanf:"app" json:"app" yaml:"app"`
	Services map[string]*ServiceConfig `koanf:"services" json:"services" yaml:"services"`
	BaseDir  string                    `koanf:"-"`
	// contains filtered or unexported fields
}

Config is the main configuration struct. App is the app config. Services is a map of service name and the corresponding config. ServiceName is the first part of the path. e.g. /petstore/v1/pets -> petstore in case, there's no service name, the name "root" will be used.

func MustConfig added in v0.1.30

func MustConfig(baseDir string) *Config

MustConfig creates a new config from a YAML file path. In case it file does not exist or has incorrect YAML: - it creates a new default config

Koanf has a file watcher, but its easier to control the changes with a manual reload.

func NewConfigFromContent added in v0.1.30

func NewConfigFromContent(content []byte) (*Config, error)

NewConfigFromContent creates a new config from a YAML file content.

func NewDefaultConfig added in v0.1.30

func NewDefaultConfig(baseDir string) *Config

NewDefaultConfig creates a new default config in case the config file is missing, not found or any other error.

func (*Config) EnsureConfigValues added in v0.1.30

func (c *Config) EnsureConfigValues()

EnsureConfigValues ensures that all config values are set.

func (*Config) GetApp added in v0.1.30

func (c *Config) GetApp() *AppConfig

func (*Config) GetServiceConfig added in v0.1.30

func (c *Config) GetServiceConfig(service string) *ServiceConfig

GetServiceConfig returns the config for a service. If the service is not found, it returns a default config.

func (*Config) Reload added in v0.1.30

func (c *Config) Reload()

type ContentExample added in v0.1.30

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

ContentExample is a struct that represents a generated cURL example.

type Document added in v0.1.30

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 EditorConfig added in v0.1.30

type EditorConfig struct {
	Theme    string `koanf:"theme" json:"theme" yaml:"theme"`
	FontSize int    `koanf:"fontSize" json:"fontSize" yaml:"fontSize"`
}

type FakeFunc added in v0.1.30

type FakeFunc func() MixedValue

FakeFunc is a function that returns a MixedValue. This is u unified way to work with different return types from fake library.

type FakeFuncFactoryWithString added in v0.1.30

type FakeFuncFactoryWithString func(value string) FakeFunc

FakeFuncFactoryWithString is a function that returns a FakeFunc.

type FileProperties added in v0.1.30

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 added in v0.1.30

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

GetPropertiesFromFilePath gets properties of a file from its path.

func (*FileProperties) IsEqual added in v0.1.30

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

IsEqual compares two FileProperties structs. Spec is not compared.

type Float64Value added in v0.1.30

type Float64Value float64

func (Float64Value) Get added in v0.1.30

func (f Float64Value) Get() any

type GenerateRequestOptions added in v0.1.30

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

type GeneratedRequest added in v0.1.30

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 *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 added in v0.1.30

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

func NewRequestFromOperation added in v0.1.30

func NewRequestFromOperation(
	options *GenerateRequestOptions,
	securityComponents SecurityComponents,
	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 added in v0.1.30

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 added in v0.1.30

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

func NewResponseFromOperation added in v0.1.30

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

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

type HTTPStatusConfig added in v0.1.30

type HTTPStatusConfig struct {
	Exact int    `koanf:"exact" json:"exact" yaml:"exact"`
	Range string `koanf:"range" json:"range" yaml:"range"`
}

func (*HTTPStatusConfig) Is added in v0.1.30

func (s *HTTPStatusConfig) Is(status int) bool

type Headers added in v0.1.30

type Headers map[string]*Parameter

Headers is a map of Parameter.

type HttpStatusFailOnConfig added in v0.1.30

type HttpStatusFailOnConfig []HTTPStatusConfig

func (HttpStatusFailOnConfig) Is added in v0.1.30

func (ss HttpStatusFailOnConfig) Is(status int) bool

type IntValue added in v0.1.30

type IntValue int

func (IntValue) Get added in v0.1.30

func (i IntValue) Get() any

type KinDocument added in v0.1.30

type KinDocument struct {
	*openapi3.T
}

KinDocument is a wrapper around openapi3.T Implements Document interface

func NewDocumentFromFile added in v0.1.30

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

NewDocumentFromFile creates a new Document from a file path

func (*KinDocument) FindOperation added in v0.1.30

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

FindOperation finds an operation by resource and method.

func (*KinDocument) GetResources added in v0.1.30

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

GetResources returns a map of resource names and their methods.

func (*KinDocument) GetSecurity added in v0.1.30

func (d *KinDocument) GetSecurity() SecurityComponents

func (*KinDocument) GetVersion added in v0.1.30

func (d *KinDocument) GetVersion() string

GetVersion returns the version of the document

type KinOperation added in v0.1.30

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

KinOperation is a wrapper around openapi3.Operation

func (*KinOperation) GetRequest added in v0.1.30

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

func (*KinOperation) GetResponse added in v0.1.30

func (op *KinOperation) GetResponse() *Response

GetResponse returns the operation response

func (*KinOperation) ID added in v0.1.30

func (op *KinOperation) ID() string

ID returns the operation ID

func (*KinOperation) Unwrap added in v0.1.30

func (op *KinOperation) Unwrap() Operation

func (*KinOperation) WithParseConfig added in v0.1.30

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

WithParseConfig sets the parse config for this operation

type KinValidator added in v0.1.30

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

func NewValidator added in v0.1.30

func NewValidator(_ Document) *KinValidator

NewValidator creates a new KinValidator from kin-openapi document.

func (*KinValidator) ValidateRequest added in v0.1.30

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

ValidateRequest validates GeneratedRequest against a schema.

func (*KinValidator) ValidateResponse added in v0.1.30

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 added in v0.1.30

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

MemoryStorage is a cache storage that stores data in memory.

func NewMemoryStorage added in v0.1.30

func NewMemoryStorage() *MemoryStorage

NewMemoryStorage creates a new MemoryStorage instance.

func (*MemoryStorage) Get added in v0.1.30

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

Get returns the value for the given key.

func (*MemoryStorage) Set added in v0.1.30

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

Set sets the value for the given key.

type MixedValue added in v0.1.30

type MixedValue interface {
	Get() any
}

MixedValue is a value that can represent string, int, float64, or bool type.

type Operation added in v0.1.30

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

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

func NewCacheOperationAdapter added in v0.1.30

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

NewCacheOperationAdapter creates a new CacheOperationAdapter instance.

type OperationDescription added in v0.1.30

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 added in v0.1.30

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   *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 added in v0.1.30

type Parameters []*Parameter

Parameters is a slice of Parameter.

type ParseConfig added in v0.1.30

type ParseConfig struct {
	MaxLevels          int  `koanf:"maxLevels" json:"maxLevels" yaml:"maxLevels"`
	MaxRecursionLevels int  `koanf:"maxRecursionLevels" json:"maxRecursionLevels" yaml:"maxRecursionLevels"`
	OnlyRequired       bool `koanf:"onlyRequired" json:"onlyRequired" yaml:"onlyRequired"`
}

ParseConfig defines the parsing configuration for a service. MaxLevels is the maximum level to parse. MaxRecursionLevels is the maximum level to parse recursively. 0 means no recursion: property will get nil value. OnlyRequired is a flag whether to include only required fields. If the spec contains deep references, this might significantly speed up parsing.

func NewParseConfig added in v0.1.30

func NewParseConfig() *ParseConfig

type ParsedContextResult added in v0.1.30

type ParsedContextResult struct {
	Result  map[string]any
	Aliases map[string]string
}

ParsedContextResult is the result of parsing a context file.

func ParseContextFile added in v0.1.30

func ParseContextFile(filePath string, fakes map[string]FakeFunc) (*ParsedContextResult, error)

ParseContextFile parses a YAML file and returns a map of context properties. Filename without extension is used as the context namespace and can be referenced: - in service config - when creating aliases

func ParseContextFromBytes added in v0.1.30

func ParseContextFromBytes(content []byte, fakes map[string]FakeFunc) (*ParsedContextResult, error)

ParseContextFromBytes byte contents from the YAML file and returns a map of context properties.

type Paths added in v0.1.30

type Paths struct {
	Base              string
	Resources         string
	Data              string
	Callbacks         string
	Contexts          string
	Docs              string
	Samples           string
	Services          string
	ServicesOpenAPI   string
	ServicesFixedRoot string
	UI                string
	ConfigFile        string
}

Paths is a struct that holds all the paths used by the application.

func NewPaths added in v0.1.30

func NewPaths(baseDir string) *Paths

type ReplaceContext added in v0.1.30

type ReplaceContext struct {
	Schema     any
	State      *ReplaceState
	AreaPrefix string
	Data       []map[string]any
	Faker      faker.Faker
}

ReplaceContext is a context that is used to replace values in schemas and contents.

Schema is a schema that is used to replace values. Currently only OpenAPI Schema is supported. It does not depend on schema provider as this is already converted to internal Schema type.

State is a state of the current replace operation. It is used to store information about the current element, including its name, index, content type etc.

AreaPrefix is a prefix that is used to identify the correct section in the context config for specific replacement area. e.g. in- then in the contexts we should have: in-header:

X-GeneratedRequest-ID: 123

in-path:

user_id: 123

Data is a list of contexts that are used to replace values. Faker is a faker instance that is used to generate fake data.

type ReplaceState added in v0.1.30

type ReplaceState struct {
	NamePath           []string
	ElementIndex       int
	IsHeader           bool
	IsPathParam        bool
	ContentType        string
	IsContentReadOnly  bool
	IsContentWriteOnly bool
	// contains filtered or unexported fields
}

ReplaceState is a struct that holds information about the current state of the replace operation.

NamePath is a slice of names of the current element. It is used to build a path to the current element. For example, "users", "name", "first".

ElementIndex is an index of the current element if required structure to generate is an array. IsHeader is a flag that indicates that the current element we're replacing is a header. IsPathParam is a flag that indicates that the current element we're replacing is a path parameter. ContentType is a content type of the current element. IsContentReadOnly is a flag that indicates that the current element we're replacing is a read-only content. This value is used only when Scheme has ReadOnly set to true.

IsContentWriteOnly is a flag that indicates that the current element we're replacing is a write-only content. This value is used only when Scheme has WriteOnly set to true.

func NewReplaceState added in v0.1.30

func NewReplaceState(opts ...ReplaceStateOption) *ReplaceState

func NewReplaceStateWithName added in v0.1.30

func NewReplaceStateWithName(name string) *ReplaceState

func (*ReplaceState) NewFrom added in v0.1.30

func (s *ReplaceState) NewFrom(src *ReplaceState) *ReplaceState

NewFrom creates a new ReplaceState instance from the given one.

func (*ReplaceState) WithOptions added in v0.1.30

func (s *ReplaceState) WithOptions(options ...ReplaceStateOption) *ReplaceState

type ReplaceStateOption added in v0.1.30

type ReplaceStateOption func(*ReplaceState)

func WithContentType added in v0.1.30

func WithContentType(value string) ReplaceStateOption

func WithElementIndex added in v0.1.30

func WithElementIndex(value int) ReplaceStateOption

func WithHeader added in v0.1.30

func WithHeader() ReplaceStateOption

func WithName added in v0.1.30

func WithName(name string) ReplaceStateOption

func WithPath added in v0.1.30

func WithPath() ReplaceStateOption

func WithReadOnly added in v0.1.30

func WithReadOnly() ReplaceStateOption

func WithWriteOnly added in v0.1.30

func WithWriteOnly() ReplaceStateOption

type Replacer added in v0.1.30

type Replacer func(ctx *ReplaceContext) any

Replacer is a function that returns a value to replace the original value with. Replacer functions are predefined and set in the correct order to be executed.

type Request added in v0.1.30

type Request struct {
	Parameters Parameters
	Body       *RequestBody
}

type RequestBody added in v0.1.30

type RequestBody struct {
	Schema *Schema
	Type   string
}

type Response added in v0.1.30

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

Response is a struct that represents an OpenAPI response.

type Schema added in v0.1.30

type Schema struct {
	Type string `json:"type,omitempty" yaml:"type,omitempty"`

	// in 3.1 examples can be an array (which is recommended)
	Examples []any `json:"examples,omitempty" yaml:"examples,omitempty"`

	// items can be a schema in 2.0, 3.0 and 3.1 or a bool in 3.1
	Items *Schema `json:"items,omitempty" yaml:"items,omitempty"`

	// Compatible with all versions
	MultipleOf    float64            `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"`
	Maximum       float64            `json:"maximum,omitempty" yaml:"maximum,omitempty"`
	Minimum       float64            `json:"minimum,omitempty" yaml:"minimum,omitempty"`
	MaxLength     int64              `json:"maxLength,omitempty" yaml:"maxLength,omitempty"`
	MinLength     int64              `json:"minLength,omitempty" yaml:"minLength,omitempty"`
	Pattern       string             `json:"pattern,omitempty" yaml:"pattern,omitempty"`
	Format        string             `json:"format,omitempty" yaml:"format,omitempty"`
	MaxItems      int64              `json:"maxItems,omitempty" yaml:"maxItems,omitempty"`
	MinItems      int64              `json:"minItems,omitempty" yaml:"minItems,omitempty"`
	MaxProperties int64              `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"`
	MinProperties int64              `json:"minProperties,omitempty" yaml:"minProperties,omitempty"`
	Required      []string           `json:"required,omitempty" yaml:"required,omitempty"`
	Enum          []any              `json:"enum,omitempty" yaml:"enum,omitempty"`
	Properties    map[string]*Schema `json:"properties,omitempty" yaml:"properties,omitempty"`
	Not           *Schema            `json:"not,omitempty" yaml:"not,omitempty"`
	Default       any                `json:"default,omitempty" yaml:"default,omitempty"`
	Nullable      bool               `json:"nullable,omitempty" yaml:"nullable,omitempty"`
	ReadOnly      bool               `json:"readOnly,omitempty" yaml:"readOnly,omitempty"`
	WriteOnly     bool               `json:"writeOnly,omitempty" yaml:"writeOnly,omitempty"`
	Example       any                `json:"example,omitempty" yaml:"example,omitempty"`
	Deprecated    bool               `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
}

Schema is a struct that represents an OpenAPI schema. It is compatible with all versions of OpenAPI. All schema provider should implement the Document and KinOperation interfaces. This provides a unified way to work with different OpenAPI parsers.

func NewSchemaFromKin added in v0.1.30

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

NewSchemaFromKin creates a new Scheme from a Kin schema

type SchemaWithContentType added in v0.1.30

type SchemaWithContentType struct {
	Schema      *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 added in v0.1.30

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

type SecurityComponents added in v0.1.30

type SecurityComponents map[string]*SecurityComponent

type ServiceCacheConfig added in v0.1.30

type ServiceCacheConfig struct {
	Schema bool `koanf:"schema" json:"schema" yaml:"schema"`
}

ServiceCacheConfig defines the cache configuration for a service. Avoid multiple schema parsing by caching the parsed schema. Default: true

func NewServiceCacheConfig added in v0.1.30

func NewServiceCacheConfig() *ServiceCacheConfig

type ServiceConfig added in v0.1.30

type ServiceConfig struct {
	Upstream            *UpstreamConfig        `koanf:"upstream" json:"upstream" yaml:"upstream"`
	Latency             time.Duration          `koanf:"latency" json:"latency" yaml:"latency"`
	Errors              *ServiceError          `koanf:"errors" json:"errors" yaml:"errors"`
	Contexts            []map[string]string    `koanf:"contexts" json:"contexts" yaml:"contexts"`
	ParseConfig         *ParseConfig           `json:"parseConfig" yaml:"parseConfig" koanf:"parseConfig"`
	Validate            *ServiceValidateConfig `koanf:"validate" json:"validate" yaml:"validate"`
	RequestTransformer  string                 `koanf:"requestTransformer" json:"requestTransformer" yaml:"requestTransformer"`
	ResponseTransformer string                 `koanf:"responseTransformer" json:"responseTransformer" yaml:"responseTransformer"`
	Cache               *ServiceCacheConfig    `koanf:"cache" json:"cache" yaml:"cache"`
}

ServiceConfig defines the configuration for a particular service. Latency is the latency to add to the response. Latency not used in the services API, only when endpoint queried directly. Errors is the error config. Contexts is the list of contexts to use for replacements. It is a map of context name defined either in the UI or filename without extension. You can refer to the name when building aliases. ParseConfig is the config for parsing the OpenAPI spec. Validate is the validation config. It is used to validate the request and/or response outside the Services API. ResponseTransformer is a callback function name which should exist inside callbacks directory and be visible to the plugin. Cache is the cache config.

func NewServiceConfig added in v0.1.30

func NewServiceConfig() *ServiceConfig

type ServiceError added in v0.1.30

type ServiceError struct {
	Chance int         `koanf:"chance" json:"chance" yaml:"chance"`
	Codes  map[int]int `koanf:"codes" json:"codes" yaml:"codes"`
	// contains filtered or unexported fields
}

ServiceError defines the error configuration for a service. Chance is the chance to return an error. In the config, it can be set with %-suffix. Codes is a map of error codes and their weights if Chance > 0. If no error codes are specified, it returns a 500 error code.

func NewServiceErrorConfig added in v0.1.30

func NewServiceErrorConfig() *ServiceError

func (*ServiceError) GetError added in v0.1.30

func (s *ServiceError) GetError() int

GetError returns an error code based on the chance and error weights. If no error weights are specified, it returns a 500 error code. If the chance is 0, it returns 0.

type ServiceValidateConfig added in v0.1.30

type ServiceValidateConfig struct {
	Request  bool `koanf:"request" json:"request" yaml:"request"`
	Response bool `koanf:"response" json:"response" yaml:"response"`
}

ServiceValidateConfig defines the validation configuration for a service. Request is a flag whether to validate the request. Default: true Response is a flag whether to validate the response. Default: false

func NewServiceValidateConfig added in v0.1.30

func NewServiceValidateConfig() *ServiceValidateConfig

type StringValue added in v0.1.30

type StringValue string

func (StringValue) Get added in v0.1.30

func (s StringValue) Get() any

type UploadedFile added in v0.1.30

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 added in v0.1.30

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

GetRequestFile gets an uploaded file from a GeneratedRequest.

type UpstreamConfig added in v0.1.30

type UpstreamConfig struct {
	URL     string                `koanf:"url" json:"url" yaml:"url"`
	Headers map[string]string     `koanf:"headers" json:"headers" yaml:"headers"`
	FailOn  *UpstreamFailOnConfig `koanf:"failOn" json:"failOn" yaml:"failOn"`
}

type UpstreamFailOnConfig added in v0.1.30

type UpstreamFailOnConfig struct {
	TimeOut    time.Duration          `koanf:"timeout" json:"timeout" yaml:"timeout"`
	HTTPStatus HttpStatusFailOnConfig `koanf:"httpStatus" json:"httpStatus" yaml:"httpStatus"`
}

type ValueReplacer added in v0.1.30

type ValueReplacer func(schemaOrContent any, state *ReplaceState) any

ValueReplacer is a function that replaces value in schema or content. This function should encapsulate all the logic, data, contexts etc. of replacing values.

func CreateValueReplacer added in v0.1.30

func CreateValueReplacer(cfg *Config, replacers []Replacer, contexts []map[string]any) ValueReplacer

CreateValueReplacer is a factory that creates a new ValueReplacer instance from the given config and contexts.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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