rest

package
v2.0.0-alpha6 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0 Imports: 47 Imported by: 0

Documentation

Index

Constants

View Source
const ACCEPT string = "Accept"
View Source
const APPLICATION_ID = "APPLICATION_ID"

add more keys here if needed

View Source
const AUTHORIZATION string = "Authorization"
View Source
const AliasExtension = "x-alias"

AliasExtension alias parameter name to a different name in the controller

View Source
const AuthorizationConfigExtension = "x-auth"

AuthorizationConfigExtension setup authorization

View Source
const BASIC_RESPONSE string = "_basic_response"
View Source
const CONTENT_TYPE_RESPONSE string = "_content_type_response"
View Source
const CREATE_COMMAND = "create"
View Source
const CommandDispatcherExtension = "x-command-dispatcher"

CommandDispatcherExtension set custom command dispatcher

View Source
const ContextExtension = "x-context"

ContextExtension set parameters directly in the context

View Source
const ContextNameExtension = "x-context-name"

ContextNameExtension alias parameter name to a different name in the context

View Source
const ControllerExtension = "x-controller"

ControllerExtension set controller

View Source
const CopyExtension = "x-copy"

CopyExtension is used to copy a field's values into another field, ignoring those that are not of the same type

View Source
const DELETE_COMMAND = "delete"
View Source
const ENTITY = "_entity"
View Source
const ENTITY_COLLECTION = "_entity_collection"
View Source
const ENTITY_ID = "_entity_id"

entity

View Source
const ERROR = "_error"
View Source
const EventStoreExtension = "x-event-store"

EventStoreExtension set custom event store

View Source
const FileExtension = "x-file"

FileExtension set staticFolder file

View Source
const FolderExtension = "x-folder"

FolderExtension set staticFolder folder

View Source
const HeaderXAccountID = "X-Account-ID"

based on recommendations here https://www.calhoun.io/pitfalls-of-context-values-and-how-to-avoid-or-mitigate-them/

View Source
const HeaderXLogLevel = "X-LOG-LEVEL"
View Source
const IdentifierExtension = "x-identifier"

IdentifierExtension set identifier

View Source
const JWTMapExtension = "x-jwt-map"

JWTMapExtension map claims to user and role

View Source
const MiddlewareExtension = "x-middleware"

MiddlewareExtension add middleware

View Source
const OPERATION_ID = "OPERATION_ID"
View Source
const OpenIDConnectUrlExtension = "openIdConnectUrl"

OpenIDConnectUrlExtension set the open id connect url

View Source
const ProjectionExtension = "x-projections"

ProjectionExtension set custom projection

View Source
const REPOSITORY = "_repository"
View Source
const RESPONSE_PREFIX string = "_httpstatus"
View Source
const RemoveExtension = "x-remove"

RemoveExtension marks a field for removal

View Source
const SEQUENCE_NO string = "sequence_no"
View Source
const SchemaExtension = "x-schema"

SchemaExtension alias for specifying the content type instead of the request body

View Source
const SkipExpiryCheckExtension = "x-skip-expiry-check"

SkipExpiryCheckExtension set the expiry check

View Source
const TemplateExtension = "x-templates"

TemplateExtension set template files

View Source
const UPDATE_COMMAND = "update"
View Source
const UPLOAD_RESPONSE string = "_upload_response"
View Source
const UniqueExtension = "x-unique"
View Source
const UploadExtension = "x-upload"

UploadExtension for the storage location of an upload

View Source
const WeOSConfigExtension = "x-weos-config"

WeOSConfigExtension weos configuration key

Variables

View Source
var API = fx.Module("rest",
	Core,
	fx.Invoke(registerHooks))
View Source
var InvalidAWSDriver = errors.New("invalid aws driver specified, must be postgres or mysql")
View Source
var Logger = fx.Module("logger",
	fx.Provide(
		Config,
		NewEcho,
	),
	fx.Invoke(RouteInitializer, registerHooks),
)

Functions

func Config

func Config() (*openapi3.T, error)

Config loads the OpenAPI spec from the environment

func ConvertStringToType

func ConvertStringToType(desiredType string, format string, value string) (interface{}, error)

ConvertStringToType convert open api schema types to go data types

func CreateHandler

func CreateHandler(ctx context.Context, command *Command, repository Repository, logger Log) (interface{}, error)

CreateHandler is used to add entities to the repository.

func DefaultReadController

func DefaultReadController(p *ControllerParams) echo.HandlerFunc

DefaultReadController handles the read operations viewing a specific item

func DefaultWriteController

func DefaultWriteController(p *ControllerParams) echo.HandlerFunc

DefaultWriteController handles the write operations (create, update, delete)

func GetAccount

func GetAccount(ctx context.Context) string

GetAccount info from context

func GetApplication

func GetApplication(ctx context.Context) string

GetApplication info from context

func GetEntityID

func GetEntityID(ctx context.Context) string

GetEntityID if it's in the context

func GetError

func GetError(ctx context.Context) error

GetError return error from context

func GetJwkUrl deprecated

func GetJwkUrl(openIdUrl string) (string, error)

Deprecated: 06/20/2022 Use GetOpenIDConfig to get the map of the entire config GetJwkUrl fetches the jwk url from the open id connect url

func GetLogLevel

func GetLogLevel(ctx context.Context) string

GetLogLevel from context

func GetOpenIDConfig

func GetOpenIDConfig(openIdUrl string, httpClient *http.Client) (map[string]interface{}, error)

GetOpenIDConfig returns map of openID content

func GetPayload

func GetPayload(ctx context.Context) []byte

GetPayload returns payload from context

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID from context

func GetUser

func GetUser(ctx context.Context) string

GetUser info from context

func JSONMarshal

func JSONMarshal(t interface{}) ([]byte, error)

JSONMarshal this marshals data without using html.escape

func LoadHttpRequestFixture

func LoadHttpRequestFixture(filename string) (*http.Request, error)

LoadHttpRequestFixture wrapper around the test helper to make it easier to use it with test table

func LoadHttpResponseFixture

func LoadHttpResponseFixture(filename string, req *http.Request) (*http.Response, error)

LoadHttpResponseFixture wrapper around the test helper to make it easier to use it with test table

func LogLevels

func LogLevels(level string) (log.Lvl, error)

Used to get the logLvl equivalent for an inputted level string

func MultiWriter

func MultiWriter(writers ...http.ResponseWriter) http.ResponseWriter

MultiWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command.

Each write is written to each listed writer, one at a time. If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list.

func NewClient

func NewClient() *http.Client

func NewControllerError

func NewControllerError(message string, err error, code int) *echo.HTTPError

func NewEcho

func NewEcho() (*echo.Echo, error)

func NewEtag

func NewEtag(entity BasicResource) string

NewEtag This takes in a contentEntity and concatenates the weosID and SequenceID

func NewRespBodyFromBytes

func NewRespBodyFromBytes(body []byte) io.ReadCloser

NewRespBodyFromBytes creates an io.ReadCloser from a byte slice that is suitable for use as an http response body.

func ResolveResponseType

func ResolveResponseType(header string, content openapi3.Content) string

func ReturnContextValues

func ReturnContextValues(ctxt interface{}) map[interface{}]interface{}

ReturnContextValues pulls out all the values stored in the context and adds it to a map to be returned

func RouteInitializer

func RouteInitializer(p RouteParams) (err error)

RouteInitializer initializes the routes for the application using the open api config

func SaveUploadedFiles

func SaveUploadedFiles(uploadFolder map[string]interface{}, file multipart.File, header *multipart.FileHeader) error

SaveUploadedFiles this is a supporting function for ConvertFormtoJson

func SecurityMiddleware

func SecurityMiddleware(p *MiddlewareParams) echo.MiddlewareFunc

func SplitEtag

func SplitEtag(Etag string) (string, string)

SplitEtag This takes an Etag and returns the weosID and sequence number

func SplitFilters

func SplitFilters(filters string) []string

SplitFilters splits multiple filters into array of filters

func ZapLogger

func ZapLogger(p *MiddlewareParams) echo.MiddlewareFunc

ZapLogger switches the echo context logger to be ZapLogger

Types

type APIConfig

type APIConfig struct {
	*ServiceConfig
	BasePath            string `json:"basePath" ,yaml:"basePath"`
	RecordingBaseFolder string
	Rest                *Rest           `json:"rest"`
	JWTConfig           *JWTConfig      `json:"jwtConfig"`
	Config              json.RawMessage `json:"config"`
	Version             string          `json:"version"`
}

type BasicResource

type BasicResource struct {
	Body     datatypes.JSONMap `gorm:"default:'[]'; null'"`
	Metadata ResourceMetadata  `gorm:"embedded"`
	// contains filtered or unexported fields
}

func (*BasicResource) AddError

func (r *BasicResource) AddError(err error)

func (*BasicResource) FromBytes

func (r *BasicResource) FromBytes(schema *openapi3.T, data []byte) (Resource, error)

FromBytes creates a new BasicResource from a schema and data

func (*BasicResource) GetBool

func (r *BasicResource) GetBool(propertyName string) bool

func (*BasicResource) GetErrors

func (r *BasicResource) GetErrors() []error

func (*BasicResource) GetFloat

func (r *BasicResource) GetFloat(propertyName string) float64

func (*BasicResource) GetID

func (r *BasicResource) GetID() string

func (*BasicResource) GetInt

func (r *BasicResource) GetInt(propertyName string) int

func (*BasicResource) GetNewChanges

func (r *BasicResource) GetNewChanges() []Resource

GetNewChanges returns the list of new events

func (*BasicResource) GetSequenceNo

func (r *BasicResource) GetSequenceNo() int64

func (*BasicResource) GetString

func (r *BasicResource) GetString(propertyName string) string

func (*BasicResource) GetType

func (r *BasicResource) GetType() string

func (*BasicResource) IsValid

func (r *BasicResource) IsValid() bool

func (*BasicResource) MarshalJSON

func (r *BasicResource) MarshalJSON() ([]byte, error)

MarshalJSON customizes the JSON encoding of BasicResource

func (*BasicResource) NewChange

func (r *BasicResource) NewChange(event *Event)

NewChange adds a new event to the list of new events

func (*BasicResource) Persist

func (r *BasicResource) Persist()

Persist clears the new events array

func (*BasicResource) UnmarshalJSON

func (r *BasicResource) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON customizes the JSON decoding of BasicResource

type CResponseType

type CResponseType struct {
	Status string `json:"status"`
	Type   string `json:"Type"`
}

type Command

type Command struct {
	Type     string          `json:"type"`
	Payload  json.RawMessage `json:"payload"`
	Metadata CommandMetadata `json:"metadata"`
}

type CommandConfig

type CommandConfig struct {
	Type     string
	Resource string
	Handler  CommandHandler
}

CommandConfig is a struct that holds the command type and the handler for that command

type CommandDispatcher

type CommandDispatcher interface {
	Dispatch(ctx context.Context, command *Command, logger Log, options *CommandOptions) (response CommandResponse, err error)
	AddSubscriber(command CommandConfig) map[string][]CommandHandler
	GetSubscribers() map[string][]CommandHandler
}

type CommandDispatcherParams

type CommandDispatcherParams struct {
	fx.In
	CommandConfigs []CommandConfig
	Logger         Log
}

type CommandDispatcherResult

type CommandDispatcherResult struct {
	fx.Out
	Dispatcher CommandDispatcher
}

func NewCommandDispatcher

func NewCommandDispatcher(p CommandDispatcherParams) CommandDispatcherResult

NewCommandDispatcher creates a new command dispatcher and registers all the command handlers

type CommandHandler

type CommandHandler func(ctx context.Context, command *Command, logger Log, options *CommandOptions) (response CommandResponse, err error)

type CommandMetadata

type CommandMetadata struct {
	EntityID      string
	SequenceNo    int
	EntityType    string
	Version       int64
	ExecutionDate *time.Time
	UserID        string
	AccountID     string
}

type CommandOptions

type CommandOptions struct {
	ResourceRepository *ResourceRepository
	DefaultProjection  Projection
	Projections        map[string]Projection
}

type CommandResponse

type CommandResponse struct {
	Success bool
	Message string
	Code    int
	Body    interface{}
}

type ContentType

type ContentType struct {
	Name   string           `json:"name"`
	Schema *openapi3.Schema `json:"fields"`
}

ContentType this makes it easier to access the content type information in the context

func GetContentType

func GetContentType(ctx context.Context) *ContentType

type Context deprecated

type Context struct {
	echo.Context
	// contains filtered or unexported fields
}

Deprecated: Context Use the Go context in the echo request instead

func New deprecated

func New(ctxt echo.Context) *Context

Deprecated: New use the context in the echo request instead

func (*Context) RequestContext

func (c *Context) RequestContext() context.Context

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

func (*Context) WithValue

func (c *Context) WithValue(parent *Context, key, val interface{}) *Context

type ContextKey

type ContextKey string
const ACCOUNT_ID ContextKey = "ACCOUNT_ID"
const COMMAND_DISPATCHER ContextKey = "_command_disptacher"
const CONTENT_TYPE ContextKey = "_contentType"
const CONTROLLER ContextKey = "_controller"
const ENTITY_FACTORY ContextKey = "_entityFactory"
const ENTITY_REPOSITORY ContextKey = "_entityRepository"
const EVENT_STORE ContextKey = "_event_store"
const FILTERS ContextKey = "_filters"
const LOG_LEVEL ContextKey = "LOG_LEVEL"
const METHODS_FOUND ContextKey = "_methods_found"

Path initializers are run per path and can be used to configure routes that are not defined in the open api spec

const MIDDLEWARES ContextKey = "_middlewares"
const PAYLOAD ContextKey = "_payload"
const PROJECTION ContextKey = "_projection"
const PROJECTIONS ContextKey = "_projections"
const REQUEST_ID ContextKey = "REQUEST_ID"
const ROLE ContextKey = "ROLE"
const SCHEMA_BUILDERS ContextKey = "_schema_builders"
const SORTS ContextKey = "_sorts"
const USER_ID ContextKey = "USER_ID"
const WEOS_ID ContextKey = "WEOS_ID"

type Controller

type Controller func(params *ControllerParams) echo.HandlerFunc

Controller is the handler for a specific operation

type ControllerConfig

type ControllerConfig struct {
	Name       string
	Controller Controller
}

type ControllerParams

type ControllerParams struct {
	Logger             Log
	CommandDispatcher  CommandDispatcher
	ResourceRepository *ResourceRepository
	DefaultProjection  *Projection
	Projections        map[string]Projection
	Schema             *openapi3.T
	PathMap            map[string]*openapi3.PathItem
	Operation          map[string]*openapi3.Operation
	Echo               *echo.Echo
	APIConfig          *APIConfig
}

type DBConfig

type DBConfig struct {
	Name        string `json:"name"`
	Host        string `json:"host"`
	User        string `json:"username"`
	Password    string `json:"password"`
	Port        int    `json:"port"`
	Database    string `json:"database"`
	Driver      string `json:"driver"`
	MaxOpen     int    `json:"max-open"`
	MaxIdle     int    `json:"max-idle"`
	MaxIdleTime int    `json:"max-idle-time"`
	AwsIam      bool   `json:"aws-iam"`
	AwsRegion   string `json:"aws-region"`
}

type DefaultCommandDispatcher

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

func (*DefaultCommandDispatcher) AddSubscriber

func (e *DefaultCommandDispatcher) AddSubscriber(command CommandConfig) map[string][]CommandHandler

func (*DefaultCommandDispatcher) Dispatch

func (e *DefaultCommandDispatcher) Dispatch(ctx context.Context, command *Command, logger Log, options *CommandOptions) (response CommandResponse, err error)

func (*DefaultCommandDispatcher) GetSubscribers

func (e *DefaultCommandDispatcher) GetSubscribers() map[string][]CommandHandler

type EchoParam

type EchoParam struct {
	fx.In
	Config *openapi3.T
}

type Entity

type Entity interface {
	ValueObject
	GetID() string
	GetType() string
}

type Event

type Event struct {
	gorm.Model
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
	Meta    EventMeta       `json:"meta" gorm:"embedded"`
	Version int             `json:"version"`
	// contains filtered or unexported fields
}

func NewResourceEvent

func NewResourceEvent(eventType string, resource Resource, tpayload map[string]interface{}) *Event

func (*Event) FromBytes

func (e *Event) FromBytes(schema *openapi3.T, data []byte) (Resource, error)

func (*Event) GetErrors

func (e *Event) GetErrors() []error

func (*Event) GetID

func (e *Event) GetID() string

func (*Event) GetNewChanges

func (e *Event) GetNewChanges() []Resource

func (*Event) GetSequenceNo

func (e *Event) GetSequenceNo() int64

func (*Event) GetType

func (e *Event) GetType() string

func (*Event) IsValid

func (e *Event) IsValid() bool

func (*Event) NewChange

func (e *Event) NewChange(event *Event)

func (*Event) Persist

func (e *Event) Persist()

type EventDispatcher

type EventDispatcher interface {
	AddSubscriber(handler EventHandlerConfig) error
	GetSubscribers(resourceType string) map[string][]EventHandler
	Dispatch(ctx context.Context, logger Log, event *Event) []error
}

type EventHandler

type EventHandler func(ctx context.Context, logger Log, event *Event) error

type EventHandlerConfig

type EventHandlerConfig struct {
	ResourceType string
	Type         string
	Handler      EventHandler
}

type EventMeta

type EventMeta struct {
	ResourceID    string `json:"resourceId"`
	ResourceType  string `json:"resourceType"`
	SequenceNo    int64  `json:"sequenceNo"`
	User          string `json:"user"`
	ApplicationID string `json:"applicationId"`
	RootID        string `json:"rootId"`
	AccountID     string `json:"accountId"`
	Created       string `json:"created"`
}

type EventSourced

type EventSourced interface {
	NewChange(event *Event)
	GetNewChanges() []Resource
	Persist()
}

type EventStore

type EventStore interface {
	Repository
	EventDispatcher
	Projection
}

type FilterProperties

type FilterProperties struct {
	Field    string        `json:"field"`
	Operator string        `json:"operator"`
	Value    interface{}   `json:"value"`
	Values   []interface{} `json:"values"`
}

FilterProperties is the properties need to use filters

func SplitFilter

func SplitFilter(filter string) *FilterProperties

SplitFilter splits a filter with a single value into the field, operator, value

type GORMParams

type GORMParams struct {
	fx.In
	Config *APIConfig
}

type GORMProjection

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

GORMProjection is a projection that uses GORM to persist events

func (*GORMProjection) AddSubscriber

func (e *GORMProjection) AddSubscriber(handler EventHandlerConfig) error

AddSubscriber adds a subscriber to the event dispatcher

func (*GORMProjection) Dispatch

func (e *GORMProjection) Dispatch(ctx context.Context, logger Log, event *Event) []error

Dispatch dispatches the event to the handlers

func (*GORMProjection) GetByKey

func (e *GORMProjection) GetByKey(ctxt context.Context, identifiers map[string]interface{}) (Resource, error)

func (*GORMProjection) GetByProperties

func (e *GORMProjection) GetByProperties(ctxt context.Context, identifiers map[string]interface{}) ([]Entity, error)

func (*GORMProjection) GetByURI

func (e *GORMProjection) GetByURI(ctxt context.Context, logger Log, uri string) (Resource, error)

func (*GORMProjection) GetEventHandlers

func (e *GORMProjection) GetEventHandlers() []EventHandlerConfig

func (*GORMProjection) GetList

func (e *GORMProjection) GetList(ctx context.Context, page int, limit int, query string, sortOptions map[string]string, filterOptions map[string]interface{}) ([]Resource, int64, error)

func (*GORMProjection) GetSubscribers

func (e *GORMProjection) GetSubscribers(resourceType string) map[string][]EventHandler

func (*GORMProjection) Persist

func (e *GORMProjection) Persist(ctxt context.Context, logger Log, resources []Resource) (errs []error)

Persist persists the events to the database

func (*GORMProjection) Remove

func (e *GORMProjection) Remove(ctxt context.Context, logger Log, resources []Resource) []error

func (*GORMProjection) ResourceDeleteHandler

func (e *GORMProjection) ResourceDeleteHandler(ctx context.Context, logger Log, event *Event) (err error)

ResourceDeleteHandler handles Delete operations

func (*GORMProjection) ResourceUpdateHandler

func (e *GORMProjection) ResourceUpdateHandler(ctx context.Context, logger Log, event *Event) (err error)

ResourceUpdateHandler handles Create Update operations

type GORMProjectionParams

type GORMProjectionParams struct {
	fx.In
	GORMDB       *gorm.DB
	EventConfigs []EventHandlerConfig `group:"eventHandlers"`
}

type GORMProjectionResult

type GORMProjectionResult struct {
	fx.Out
	Dispatcher        EventStore
	DefaultProjection Projection `name:"defaultProjection"`
}

func NewGORMProjection

func NewGORMProjection(p GORMProjectionParams) (result GORMProjectionResult, err error)

type GORMResult

type GORMResult struct {
	fx.Out
	GORMDB *gorm.DB
	SQLDB  *sql.DB
}

func NewGORM

func NewGORM(p GORMParams) (GORMResult, error)

type GlobalInitializer

type GlobalInitializer func(context.Context, *openapi3.T) (context.Context, error)

OperationInitializer initialzers that are run when processing OpenAPI operations

type HealthCheckResponse

type HealthCheckResponse struct {
	Version string `json:"version"`
}

HealthCheckResponse used int he health check controller to return a response with version

type JWTConfig

type JWTConfig struct {
	Key             string                 `json:"key"`         //Signing key needed for validating token
	SigningKeys     map[string]interface{} `json:"signingKeys"` //Key map used for validating token.  Can be used in place of a single key
	Certificate     []byte                 `json:"certificate"`
	CertificatePath string                 `json:"certificatePath"` //Path the signing certificate used to validate token.  Can  be used in place of a key
	JWKSUrl         string                 `json:"jwksUrl"`         //URL to JSON Web Key set.  Can be used in place of a Key
	TokenLookup     string                 `json:"tokenLookup"`
	Claims          map[string]interface{} `json:"claims"`
	AuthScheme      string                 `json:"authScheme"`
	ContextKey      string                 `json:"contextKey"`
	SigningMethod   string                 `json:"signingMethod"`
}

type ListApiResponse

type ListApiResponse struct {
	Total int64           `json:"total"`
	Page  int             `json:"page"`
	Items []BasicResource `json:"items"`
}

ListApiResponse used in the list controller to return a response with total, page and items retrieved

type Log

type Log interface {
	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Printf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
	Panicf(format string, args ...interface{})

	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Print(args ...interface{})
	Error(args ...interface{})
	Fatal(args ...interface{})
	Panic(args ...interface{})
}

type LogConfig

type LogConfig struct {
	Level        string `json:"level"`
	Name         string `json:"name"`
	ReportCaller bool   `json:"report-caller"`
	Formatter    string `json:"formatter"`
}

type LoggerResult

type LoggerResult struct {
	fx.Out
	Logger Log
}

func NewZap

func NewZap() (LoggerResult, error)

type Middleware

type Middleware func(params *MiddlewareParams) echo.MiddlewareFunc

Middleware that is bound to an OpenAPI operation

type MiddlewareConfig

type MiddlewareConfig struct {
	Name       string
	Middleware Middleware
}

type MiddlewareParams

type MiddlewareParams struct {
	Logger                Log
	CommandDispatcher     CommandDispatcher
	ResourceRepository    *ResourceRepository
	Schema                *openapi3.T
	APIConfig             *APIConfig
	PathMap               map[string]*openapi3.PathItem
	Operation             map[string]*openapi3.Operation
	SecuritySchemes       map[string]Validator
	AuthorizationEnforcer *casbin.Enforcer
}

type OAuth2

type OAuth2 struct {
	Flows *openapi3.OAuthFlows
	// contains filtered or unexported fields
}

func (*OAuth2) FromSchema

func (o *OAuth2) FromSchema(ctxt context.Context, scheme *openapi3.SecurityScheme, client *http.Client) (Validator, error)

func (*OAuth2) Validate

func (o *OAuth2) Validate(ctxt echo.Context) (*ValidationResult, error)

type OpenIDConnect

type OpenIDConnect struct {
	KeySet oidc.KeySet
	// contains filtered or unexported fields
}

OpenIDConnect authorizer for OpenID

func (*OpenIDConnect) FromSchema

func (o *OpenIDConnect) FromSchema(ctxt context.Context, scheme *openapi3.SecurityScheme, httpClient *http.Client) (Validator, error)

func (*OpenIDConnect) Validate

func (o *OpenIDConnect) Validate(ctxt echo.Context) (result *ValidationResult, err error)

type PathConfig

type PathConfig struct {
	Handler        string          `json:"handler" ,yaml:"handler"`
	Group          bool            `json:"group" ,yaml:"group"`
	Middleware     []string        `json:"middleware"`
	Config         json.RawMessage `json:"config"`
	DisableCors    bool            `json:"disable-cors"`
	AllowedHeaders []string        `json:"allowed-headers" ,yaml:"allowed-headers"`
	AllowedOrigins []string        `json:"allowed-origins" ,yaml:"allowed-origins"`
}

type Projection

type Projection interface {
	GetByURI(ctxt context.Context, logger Log, uri string) (Resource, error)
	// GetByKey returns a single content entity
	GetByKey(ctxt context.Context, identifiers map[string]interface{}) (Resource, error)
	// GetList returns a paginated result of content entities
	GetList(ctx context.Context, page int, limit int, query string, sortOptions map[string]string, filterOptions map[string]interface{}) ([]Resource, int64, error)
	GetByProperties(ctxt context.Context, identifiers map[string]interface{}) ([]Entity, error)
	GetEventHandlers() []EventHandlerConfig
}

type QueryProperties

type QueryProperties struct {
	Value string `json:"value"`
	Field string `json:"field"`
}

QueryProperties is the properties needed to use key value pair query parameters

func SplitQueryParameters

func SplitQueryParameters(query string, key string) *QueryProperties

SplitQueryParameters is used to split key value pair query parameters

type Repository

type Repository interface {
	Persist(ctxt context.Context, logger Log, resources []Resource) []error
	Remove(ctxt context.Context, logger Log, resources []Resource) []error
}

type Resource

type Resource interface {
	EventSourced
	GetType() string
	GetSequenceNo() int64
	GetID() string
	FromBytes(schema *openapi3.T, data []byte) (Resource, error)
	IsValid() bool
	GetErrors() []error
}

type ResourceCreateParams

type ResourceCreateParams struct {
	Resource Resource
	Schema   *openapi3.Schema
}

type ResourceMetadata

type ResourceMetadata struct {
	ID         string `gorm:"primaryKey"`
	SequenceNo int64
	Type       string
	Version    int
	UserID     string
	AccountID  string
}

type ResourceRepository

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

func (*ResourceRepository) GetDefaultProjection

func (r *ResourceRepository) GetDefaultProjection() Projection

func (*ResourceRepository) GetProjections

func (r *ResourceRepository) GetProjections() []Projection

func (*ResourceRepository) Initialize

func (r *ResourceRepository) Initialize(ctxt context.Context, logger Log, payload []byte) (resource Resource, err error)

func (*ResourceRepository) Persist

func (r *ResourceRepository) Persist(ctxt context.Context, logger Log, resources []Resource) []error

func (*ResourceRepository) Remove

func (r *ResourceRepository) Remove(ctxt context.Context, logger Log, resources []Resource) error

type ResourceRepositoryParams

type ResourceRepositoryParams struct {
	fx.In
	EventStore        EventStore
	Projections       []Projection `group:"projections"`
	DefaultProjection Projection   `name:"defaultProjection" optional:"true"`
	Config            *openapi3.T
}

type ResourceRepositoryResult

type ResourceRepositoryResult struct {
	fx.Out
	Repository *ResourceRepository
}

func NewResourceRepository

func NewResourceRepository(p ResourceRepositoryParams) (ResourceRepositoryResult, error)

NewResourceRepository creates a new resource repository and registers all the event handlers

type Rest

type Rest struct {
	Middleware    []string `json:"x-middleware"`
	PreMiddleware []string `json:"pre-middleware"`
}

type RouteParams

type RouteParams struct {
	fx.In
	Config                *openapi3.T
	APIConfig             *APIConfig
	Echo                  *echo.Echo
	Logger                Log
	CommandDispatcher     CommandDispatcher
	ResourceRepository    *ResourceRepository
	Controllers           []map[string]Controller `group:"controllers"`
	Middlewares           []map[string]Middleware `group:"middlewares"`
	GORMDB                *gorm.DB
	AuthorizationEnforcer *casbin.Enforcer
	SecuritySchemes       map[string]Validator
}

type SecurityConfiguration

type SecurityConfiguration struct {
	fx.Out
	SecuritySchemes map[string]Validator
	AuthEnforcer    *casbin.Enforcer
}

func NewSecurityConfiguration

func NewSecurityConfiguration(p SecurityParams) (result SecurityConfiguration, err error)

type SecurityParams

type SecurityParams struct {
	fx.In
	Config     *openapi3.T
	HttpClient *http.Client
	GORMDB     *gorm.DB
}

type ServiceConfig

type ServiceConfig struct {
	ModuleID      string      `json:"moduleId"`
	Title         string      `json:"title"`
	AccountID     string      `json:"accountId"`
	ApplicationID string      `json:"applicationId"`
	AccountName   string      `json:"accountName"`
	Database      *DBConfig   `json:"database"`
	Databases     []*DBConfig `json:"databases"`
	Log           *LogConfig  `json:"log"`
	BaseURL       string      `json:"baseURL"`
	LoginURL      string      `json:"loginURL"`
	GraphQLURL    string      `json:"graphQLURL"`
	SessionKey    string      `json:"sessionKey"`
	Secret        string      `json:"secret"`
	AccountURL    string      `json:"accountURL"`
}

type ValidationResult

type ValidationResult struct {
	Valid         bool
	Token         string
	UserID        string
	Role          string
	AccountID     string
	ApplicationID string
}

ValidationResult is the result of a security validation

type Validator

type Validator interface {
	Validate(ctxt echo.Context) (*ValidationResult, error)
	FromSchema(ctx context.Context, scheme *openapi3.SecurityScheme, httpClient *http.Client) (Validator, error)
}

type ValueObject

type ValueObject interface {
	IsValid() bool
	AddError(err error)
	GetErrors() []error
}

type WeOSConfigParams

type WeOSConfigParams struct {
	fx.In
	Config *openapi3.T
	Logger Log
}

type WeOSConfigResult

type WeOSConfigResult struct {
	fx.Out
	Config *APIConfig
}

func WeOSConfig

func WeOSConfig(p WeOSConfigParams) (WeOSConfigResult, error)

type Zap

type Zap struct {
	*zap.SugaredLogger
	// contains filtered or unexported fields
}

func (*Zap) Debug

func (z *Zap) Debug(args ...interface{})

func (*Zap) Debugf

func (z *Zap) Debugf(format string, args ...interface{})

func (*Zap) Debugj

func (z *Zap) Debugj(j log.JSON)

func (*Zap) Error

func (z *Zap) Error(args ...interface{})

func (*Zap) Errorf

func (z *Zap) Errorf(format string, args ...interface{})

func (*Zap) Errorj

func (z *Zap) Errorj(j log.JSON)

func (*Zap) Fatalj

func (z *Zap) Fatalj(j log.JSON)

func (*Zap) Infoj

func (z *Zap) Infoj(j log.JSON)

func (*Zap) Level

func (z *Zap) Level() log.Lvl

func (*Zap) Output

func (z *Zap) Output() io.Writer

func (*Zap) Panicj

func (z *Zap) Panicj(j log.JSON)

func (*Zap) Prefix

func (z *Zap) Prefix() string

func (*Zap) Print

func (z *Zap) Print(args ...interface{})

func (*Zap) Printf

func (z *Zap) Printf(format string, args ...interface{})

func (*Zap) Printj

func (z *Zap) Printj(j log.JSON)

func (*Zap) SetHeader

func (z *Zap) SetHeader(h string)

func (*Zap) SetLevel

func (z *Zap) SetLevel(v log.Lvl)

func (*Zap) SetOutput

func (z *Zap) SetOutput(w io.Writer)

func (*Zap) SetPrefix

func (z *Zap) SetPrefix(p string)

func (*Zap) Warn

func (z *Zap) Warn(args ...interface{})

func (*Zap) Warnf

func (z *Zap) Warnf(format string, args ...interface{})

func (*Zap) Warnj

func (z *Zap) Warnj(j log.JSON)

func (*Zap) WithRequestID

func (z *Zap) WithRequestID(prefix string, level string, requestID string) (*Zap, error)

Jump to

Keyboard shortcuts

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