Documentation
¶
Index ¶
- Constants
- Variables
- func ActivityEmitterFromContext(ctx context.Context) *activity.Emitter
- func BoolPtr(v bool) *bool
- func ContextWithActivityEmitter(ctx context.Context, emitter *activity.Emitter) context.Context
- func ContextWithActor(ctx context.Context, actor ActorContext) context.Context
- func ContextWithCorrelationID(ctx context.Context, correlationID string) context.Context
- func ContextWithHookMetadata(ctx context.Context, meta HookMetadata) context.Context
- func ContextWithNotificationEmitter(ctx context.Context, emitter NotificationEmitter) context.Context
- func ContextWithRequestID(ctx context.Context, requestID string) context.Context
- func ContextWithScope(ctx context.Context, scope ScopeFilter) context.Context
- func CorrelationIDFromContext(ctx context.Context) string
- func DefaultDeserializer[T any](op CrudOperation, ctx Context) (T, error)
- func DefaultDeserializerMany[T any](op CrudOperation, ctx Context) ([]T, error)
- func DefaultOperatorMap() map[string]string
- func GetResourceName(typ reflect.Type) (string, string)
- func GetResourceTitle(typ reflect.Type) (string, string)
- func LogFieldPolicyDecision(logger Logger, audit FieldPolicyAudit)
- func RegisterSchemaListener(listener SchemaListener)
- func RequestIDFromContext(ctx context.Context) string
- func SendNotification[T any](hctx HookContext, phase ActivityPhase, record T, ...) error
- func SendNotificationBatch[T any](hctx HookContext, phase ActivityPhase, records []T, ...) error
- func SetOperatorMap(om map[string]string)
- func StringPtr(v string) *string
- func VirtualFieldExpr(dialect, sourceField, key string, asJSON bool) string
- func WithProblemJSONContentType(contentType string) problemJSONEncoderOption
- func WithProblemJSONErrorMappers(mappers ...goerrors.ErrorMapper) problemJSONEncoderOption
- func WithProblemJSONIncludeStack(include bool) problemJSONEncoderOption
- func WithProblemJSONStatusResolver(resolver ErrorStatusResolver) problemJSONEncoderOption
- type APIListResponse
- type APIResponse
- type Action
- type ActionContext
- type ActionDescriptor
- type ActionHandler
- type ActionTarget
- type ActivityPhase
- type ActorContext
- type AdminMenuMetadata
- type AdminScopeMetadata
- type CommandServiceFactory
- type Context
- type Controller
- func (c *Controller[T]) Create(ctx Context) error
- func (c *Controller[T]) CreateBatch(ctx Context) error
- func (c *Controller[T]) Delete(ctx Context) error
- func (c *Controller[T]) DeleteBatch(ctx Context) error
- func (c *Controller[T]) GetMetadata() router.ResourceMetadata
- func (c *Controller[T]) Index(ctx Context) error
- func (c *Controller[T]) RegisterRoutes(r Router)
- func (c *Controller[T]) Schema(ctx Context) error
- func (c *Controller[T]) Show(ctx Context) error
- func (c *Controller[T]) Update(ctx Context) error
- func (c *Controller[T]) UpdateBatch(ctx Context) error
- type CrudOperation
- type DefaultResponseHandler
- func (h *DefaultResponseHandler[T]) OnData(c Context, data T, op CrudOperation, filters ...*Filters) error
- func (h *DefaultResponseHandler[T]) OnEmpty(c Context, op CrudOperation) error
- func (h *DefaultResponseHandler[T]) OnError(c Context, err error, op CrudOperation) error
- func (h *DefaultResponseHandler[T]) OnList(c Context, data []T, op CrudOperation, filters *Filters) error
- type ErrorEncoder
- type ErrorStatusResolver
- type FieldMapProvider
- type FieldMaskFunc
- type FieldPolicy
- type FieldPolicyAudit
- type FieldPolicyProvider
- type FieldPolicyRequest
- type Fields
- type Filters
- type HookBatchFunc
- type HookContext
- type HookFunc
- type HookMetadata
- type LifecycleHooks
- type Logger
- type MergePolicy
- type MetadataRouterRouteInfo
- type NotFoundError
- type NotificationEmitter
- type NotificationEvent
- type NotificationEventOption
- type Option
- func WithActions[T any](actions ...Action[T]) Option[T]
- func WithActivityHooks[T any](hooks activity.Hooks, cfg activity.Config) Option[T]
- func WithAdminMenuMetadata[T any](meta AdminMenuMetadata) Option[T]
- func WithAdminScopeMetadata[T any](meta AdminScopeMetadata) Option[T]
- func WithBatchReturnOrderByID[T any](enabled bool) Option[T]
- func WithBatchRouteSegment[T any](segment string) Option[T]
- func WithCommandService[T any](factory CommandServiceFactory[T]) Option[T]
- func WithDeserializer[T any](d func(CrudOperation, Context) (T, error)) Option[T]
- func WithErrorEncoder[T any](encoder ErrorEncoder) Option[T]
- func WithFieldMapProvider[T any](provider FieldMapProvider) Option[T]
- func WithFieldPolicyProvider[T any](provider FieldPolicyProvider[T]) Option[T]
- func WithLifecycleHooks[T any](hooks LifecycleHooks[T]) Option[T]
- func WithLogger[T any](logger Logger) Option[T]
- func WithNotificationEmitter[T any](emitter NotificationEmitter) Option[T]
- func WithQueryLogging[T any](enabled bool) Option[T]
- func WithRelationFilter[T any](filter router.RelationFilterFunc) Option[T]
- func WithRelationMetadataProvider[T any](provider router.RelationMetadataProvider) Option[T]
- func WithResponseHandler[T any](handler ResponseHandler[T]) Option[T]
- func WithRouteConfig[T any](config RouteConfig) Option[T]
- func WithRowFilterHints[T any](hints ...RowFilterHint) Option[T]
- func WithScopeGuard[T any](guard ScopeGuardFunc[T]) Option[T]
- func WithService[T any](service Service[T]) Option[T]
- func WithServiceFuncs[T any](overrides ServiceFuncs[T]) Option[T]
- func WithVirtualFields[T any](cfg ...VirtualFieldHandlerConfig) Option[T]
- type Order
- type QueryBuilderOption
- type RelationFilter
- type RelationInfo
- type RepositoryServiceOptions
- type Request
- type ResourceController
- type ResourceHandler
- type Response
- type ResponseHandler
- type RouteConfig
- type RouteOptions
- type Router
- type RouterRouteInfo
- type RowFilterHint
- type SchemaEntry
- type SchemaListener
- type ScopeColumnFilter
- type ScopeFilter
- type ScopeGuardFunc
- type Service
- func ComposeService[T any](defaults Service[T], funcs ServiceFuncs[T]) Service[T]
- func NewRepositoryService[T any](repo repository.Repository[T]) Service[T]
- func NewRepositoryServiceWithOptions[T any](repo repository.Repository[T], opts RepositoryServiceOptions) Service[T]
- func NewService[T any](cfg ServiceConfig[T]) Service[T]
- func NewServiceFromFuncs[T any](repo repository.Repository[T], funcs ServiceFuncs[T]) Service[T]
- type ServiceConfig
- type ServiceFuncs
- type ValidationError
- type ValidatorFunc
- type VirtualFieldDef
- type VirtualFieldHandler
- type VirtualFieldHandlerConfig
- type VirtualFieldProcessor
Constants ¶
const ( TAG_CRUD = "crud" TAG_BUN = "bun" TAG_JSON = "json" TAG_KEY_RESOURCE = "resource" )
const ( VirtualDialectPostgres = persistence.VirtualDialectPostgres VirtualDialectSQLite = persistence.VirtualDialectSQLite )
Variables ¶
var DefaultLimit = 25
var DefaultOffset = 0
var LoggerEnabled = false
Functions ¶
func ActivityEmitterFromContext ¶ added in v0.14.0
ActivityEmitterFromContext returns the hook activity emitter stored on the context.
func ContextWithActivityEmitter ¶ added in v0.14.0
ContextWithActivityEmitter stores the activity emitter used by hooks.
func ContextWithActor ¶ added in v0.12.0
func ContextWithActor(ctx context.Context, actor ActorContext) context.Context
ContextWithActor stores the provided actor metadata on the standard context.
func ContextWithCorrelationID ¶ added in v0.12.0
ContextWithCorrelationID stores the correlation ID on the context.
func ContextWithHookMetadata ¶ added in v0.14.0
func ContextWithHookMetadata(ctx context.Context, meta HookMetadata) context.Context
ContextWithHookMetadata attaches hook metadata to the context.
func ContextWithNotificationEmitter ¶ added in v0.14.0
func ContextWithNotificationEmitter(ctx context.Context, emitter NotificationEmitter) context.Context
ContextWithNotificationEmitter stores the notification emitter for hooks.
func ContextWithRequestID ¶ added in v0.12.0
ContextWithRequestID stores the current request identifier on the context.
func ContextWithScope ¶ added in v0.12.0
func ContextWithScope(ctx context.Context, scope ScopeFilter) context.Context
ContextWithScope stores the guard scope filter on the context.
func CorrelationIDFromContext ¶ added in v0.12.0
CorrelationIDFromContext extracts the stored correlation ID.
func DefaultDeserializer ¶
func DefaultDeserializer[T any](op CrudOperation, ctx Context) (T, error)
DefaultDeserializer provides a generic deserializer.
func DefaultDeserializerMany ¶ added in v0.1.0
func DefaultDeserializerMany[T any](op CrudOperation, ctx Context) ([]T, error)
DefaultDeserializerMany provides a generic deserializer.
func DefaultOperatorMap ¶
func GetResourceName ¶
GetResourceName returns the singular and plural resource names for type T. It first checks for a 'crud:"resource:..."' tag on any embedded fields. If found, it uses the specified resource name. Otherwise, it derives the name from the type's name.
func LogFieldPolicyDecision ¶ added in v0.12.0
func LogFieldPolicyDecision(logger Logger, audit FieldPolicyAudit)
LogFieldPolicyDecision writes the audit entry using the provided logger.
func RegisterSchemaListener ¶ added in v0.12.0
func RegisterSchemaListener(listener SchemaListener)
RegisterSchemaListener subscribes to schema updates.
func RequestIDFromContext ¶ added in v0.12.0
RequestIDFromContext returns the request identifier stored in the context.
func SendNotification ¶ added in v0.12.0
func SendNotification[T any](hctx HookContext, phase ActivityPhase, record T, opts ...NotificationEventOption) error
SendNotification emits a notification event for a single record.
func SendNotificationBatch ¶ added in v0.12.0
func SendNotificationBatch[T any](hctx HookContext, phase ActivityPhase, records []T, opts ...NotificationEventOption) error
SendNotificationBatch emits a notification event for multiple records.
func SetOperatorMap ¶
func VirtualFieldExpr ¶ added in v0.14.0
VirtualFieldExpr returns a SQL snippet for the given dialect to access a virtual field. When asJSON is false, text extraction is used (suitable for comparisons/order-by). When asJSON is true, the raw JSON value is returned.
func WithProblemJSONContentType ¶ added in v0.12.0
func WithProblemJSONContentType(contentType string) problemJSONEncoderOption
WithProblemJSONContentType overrides the response content type (defaults to application/problem+json).
func WithProblemJSONErrorMappers ¶ added in v0.12.0
func WithProblemJSONErrorMappers(mappers ...goerrors.ErrorMapper) problemJSONEncoderOption
WithProblemJSONErrorMappers appends additional error mappers.
func WithProblemJSONIncludeStack ¶ added in v0.12.0
func WithProblemJSONIncludeStack(include bool) problemJSONEncoderOption
WithProblemJSONIncludeStack configures whether stack traces should be serialized.
func WithProblemJSONStatusResolver ¶ added in v0.12.0
func WithProblemJSONStatusResolver(resolver ErrorStatusResolver) problemJSONEncoderOption
WithProblemJSONStatusResolver overrides the status resolver used by the encoder.
Types ¶
type APIListResponse ¶ added in v0.0.2
type APIResponse ¶ added in v0.0.2
type Action ¶ added in v0.12.0
type Action[T any] struct { Name string Method string Target ActionTarget Path string Summary string Description string Tags []string Parameters []router.Parameter RequestBody *router.RequestBody Responses []router.Response Security []string Handler ActionHandler[T] }
Action describes a custom endpoint registered alongside the CRUD routes.
type ActionContext ¶ added in v0.12.0
type ActionContext[T any] struct { Context Actor ActorContext Scope ScopeFilter RequestID string CorrelationID string Action ActionDescriptor Operation CrudOperation }
ActionContext extends the base Context with actor/scope metadata for convenience.
type ActionDescriptor ¶ added in v0.12.0
type ActionDescriptor struct {
Name string `json:"name"`
Slug string `json:"slug"`
Method string `json:"method"`
Target ActionTarget `json:"target"`
Path string `json:"path"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
}
ActionDescriptor is a normalized view of the action exposed via metadata.
type ActionHandler ¶ added in v0.12.0
type ActionHandler[T any] func(ActionContext[T]) error
ActionHandler executes the custom action logic. Use the embedded Context to write responses.
type ActionTarget ¶ added in v0.12.0
type ActionTarget string
ActionTarget indicates whether the action targets the collection or a specific record.
const ( ActionTargetCollection ActionTarget = "collection" ActionTargetResource ActionTarget = "resource" )
type ActivityPhase ¶ added in v0.12.0
type ActivityPhase string
ActivityPhase indicates the lifecycle moment that triggered the emitter.
const ( ActivityPhaseBefore ActivityPhase = "before" ActivityPhaseAfter ActivityPhase = "after" ActivityPhaseError ActivityPhase = "error" )
type ActorContext ¶ added in v0.12.0
type ActorContext struct {
ActorID string
Subject string
Role string
ResourceRoles map[string]string
TenantID string
OrganizationID string
Metadata map[string]any
ImpersonatorID string
IsImpersonated bool
}
ActorContext captures normalized actor metadata attached to a request. It mirrors the payload emitted by go-auth middleware so guard adapters can run without importing that package.
func ActorFromContext ¶ added in v0.12.0
func ActorFromContext(ctx context.Context) ActorContext
ActorFromContext retrieves the ActorContext previously stored on the context.
func (ActorContext) Clone ¶ added in v0.12.0
func (a ActorContext) Clone() ActorContext
Clone returns a shallow copy guarding internal maps from mutation.
func (ActorContext) IsZero ¶ added in v0.12.0
func (a ActorContext) IsZero() bool
IsZero reports whether the actor context carries any meaningful identifier.
type AdminMenuMetadata ¶ added in v0.12.0
type AdminMenuMetadata struct {
Group string `json:"group,omitempty"`
Label string `json:"label,omitempty"`
Icon string `json:"icon,omitempty"`
Order int `json:"order,omitempty"`
Path string `json:"path,omitempty"`
Hidden bool `json:"hidden,omitempty"`
}
AdminMenuMetadata hints how the CMS should organize the resource.
type AdminScopeMetadata ¶ added in v0.12.0
type AdminScopeMetadata struct {
Level string `json:"level,omitempty"`
Description string `json:"description,omitempty"`
Claims []string `json:"claims,omitempty"`
Roles []string `json:"roles,omitempty"`
Labels []string `json:"labels,omitempty"`
}
AdminScopeMetadata documents the required scope/claims for a resource.
type CommandServiceFactory ¶ added in v0.12.0
CommandServiceFactory builds a Service implementation that can wrap the controller's default service (repository-backed) with command adapters.
func CommandServiceFromFuncs ¶ added in v0.12.0
func CommandServiceFromFuncs[T any](overrides ServiceFuncs[T]) CommandServiceFactory[T]
CommandServiceFromFuncs returns a CommandServiceFactory that applies the given overrides on top of the provided defaults. It is useful when command adapters only need to intercept a subset of operations.
type Controller ¶
type Controller[T any] struct { Repo repository.Repository[T] // contains filtered or unexported fields }
Controller handles CRUD operations for a given model.
func NewController ¶
func NewController[T any](repo repository.Repository[T], opts ...Option[T]) *Controller[T]
NewController creates a new Controller with functional options.
func NewControllerWithService ¶ added in v0.14.0
func NewControllerWithService[T any](repo repository.Repository[T], service Service[T], opts ...Option[T]) *Controller[T]
NewControllerWithService builds a controller using the provided service while still honoring controller options (deserializer, response handler, hooks, etc.).
func (*Controller[T]) Create ¶
func (c *Controller[T]) Create(ctx Context) error
func (*Controller[T]) CreateBatch ¶ added in v0.1.0
func (c *Controller[T]) CreateBatch(ctx Context) error
func (*Controller[T]) Delete ¶
func (c *Controller[T]) Delete(ctx Context) error
func (*Controller[T]) DeleteBatch ¶ added in v0.1.0
func (c *Controller[T]) DeleteBatch(ctx Context) error
func (*Controller[T]) GetMetadata ¶ added in v0.1.1
func (c *Controller[T]) GetMetadata() router.ResourceMetadata
GetMetadata implements router.MetadataProvider, we use it to generate the required info that will be used to create a OpenAPI spec or something similar
func (*Controller[T]) Index ¶ added in v0.1.0
func (c *Controller[T]) Index(ctx Context) error
Index supports different query string parameters: GET /users?limit=10&offset=20 GET /users?order=name asc,created_at desc GET /users?select=id,name,email GET /users?include=company,profile GET /users?name__ilike=John&age__gte=30 GET /users?name__and=John,Jack GET /users?name__or=John,Jack
func (*Controller[T]) RegisterRoutes ¶
func (c *Controller[T]) RegisterRoutes(r Router)
func (*Controller[T]) Schema ¶ added in v0.2.0
func (c *Controller[T]) Schema(ctx Context) error
func (*Controller[T]) Show ¶ added in v0.1.0
func (c *Controller[T]) Show(ctx Context) error
Show supports different query string parameters: GET /user?include=Company,Profile GET /user?select=id,age,email
func (*Controller[T]) Update ¶
func (c *Controller[T]) Update(ctx Context) error
func (*Controller[T]) UpdateBatch ¶ added in v0.1.0
func (c *Controller[T]) UpdateBatch(ctx Context) error
type CrudOperation ¶
type CrudOperation string
CrudOperation defines the type for CRUD operations.
const ( OpCreate CrudOperation = "create" OpCreateBatch CrudOperation = "create:batch" OpRead CrudOperation = "read" OpList CrudOperation = "list" OpUpdate CrudOperation = "update" OpUpdateBatch CrudOperation = "update:batch" OpDelete CrudOperation = "delete" OpDeleteBatch CrudOperation = "delete:batch" )
type DefaultResponseHandler ¶ added in v0.0.2
type DefaultResponseHandler[T any] struct { // contains filtered or unexported fields }
func (*DefaultResponseHandler[T]) OnData ¶ added in v0.0.2
func (h *DefaultResponseHandler[T]) OnData(c Context, data T, op CrudOperation, filters ...*Filters) error
func (*DefaultResponseHandler[T]) OnEmpty ¶ added in v0.0.2
func (h *DefaultResponseHandler[T]) OnEmpty(c Context, op CrudOperation) error
func (*DefaultResponseHandler[T]) OnError ¶ added in v0.0.2
func (h *DefaultResponseHandler[T]) OnError(c Context, err error, op CrudOperation) error
func (*DefaultResponseHandler[T]) OnList ¶ added in v0.0.2
func (h *DefaultResponseHandler[T]) OnList(c Context, data []T, op CrudOperation, filters *Filters) error
type ErrorEncoder ¶ added in v0.12.0
type ErrorEncoder func(ctx Context, err error, op CrudOperation) error
ErrorEncoder serializes controller errors into HTTP responses.
func LegacyJSONErrorEncoder ¶ added in v0.12.0
func LegacyJSONErrorEncoder() ErrorEncoder
LegacyJSONErrorEncoder preserves the previous {success:false,error:string} payloads.
func ProblemJSONErrorEncoder ¶ added in v0.12.0
func ProblemJSONErrorEncoder(opts ...problemJSONEncoderOption) ErrorEncoder
ProblemJSONErrorEncoder returns an encoder that emits go-errors compatible RFC-7807/problem+json responses. The encoder inspects known error categories, maps them to HTTP status codes, and writes go-errors.ErrorResponse bodies.
type ErrorStatusResolver ¶ added in v0.12.0
type ErrorStatusResolver func(err *goerrors.Error, op CrudOperation) int
ErrorStatusResolver resolves the HTTP status code for a go-errors error.
type FieldMapProvider ¶ added in v0.4.0
func NewVirtualFieldMapProvider ¶ added in v0.14.0
func NewVirtualFieldMapProvider(cfg VirtualFieldHandlerConfig, base FieldMapProvider) FieldMapProvider
NewVirtualFieldMapProvider builds a FieldMapProvider that merges the base provider with virtual field expressions. It inspects model tags to discover virtual fields and emits dialect-aware expressions.
type FieldMaskFunc ¶ added in v0.12.0
FieldMaskFunc receives the current field value and returns the masked version. Returning nil will zero the field when serialized.
type FieldPolicy ¶ added in v0.12.0
type FieldPolicy struct {
// Name helps auditors identify which policy executed (e.g., "tenant-admin").
Name string
// Allow restricts responses to the listed JSON field names. Empty means inherit defaults.
Allow []string
// Deny removes the listed JSON field names from the response/queryable set.
Deny []string
// Mask applies field-level transformations before encoding the response.
Mask map[string]FieldMaskFunc
// RowFilter appends additional column filters after guard enforcement.
RowFilter ScopeFilter
// Labels stores arbitrary metadata surfaced in audit logs.
Labels map[string]string
}
FieldPolicy describes per-request column visibility rules returned by FieldPolicyProvider.
type FieldPolicyAudit ¶ added in v0.12.0
type FieldPolicyAudit struct {
Policy string
Resource string
Operation CrudOperation
Allowed []string
Denied []string
Masked []string
RowFilter []ScopeColumnFilter
Labels map[string]string
}
FieldPolicyAudit captures the normalized details emitted to logs.
type FieldPolicyProvider ¶ added in v0.12.0
type FieldPolicyProvider[T any] func(FieldPolicyRequest[T]) (FieldPolicy, error)
FieldPolicyProvider returns the policy governing the given request.
type FieldPolicyRequest ¶ added in v0.12.0
type FieldPolicyRequest[T any] struct { Context Context Operation CrudOperation Actor ActorContext Scope ScopeFilter Resource string ResourceTyp reflect.Type }
FieldPolicyRequest conveys the context supplied to FieldPolicyProvider.
type Filters ¶ added in v0.1.0
type Filters struct {
Operation string `json:"operation,omitempty"`
Limit int `json:"limit,omitempty"`
Offset int `json:"offset,omitempty"`
Page int `json:"page,omitempty"`
Adjusted bool `json:"adjusted,omitempty"`
Count int `json:"count,omitempty"`
Order []Order `json:"order,omitempty"`
Fields []string `json:"fields,omitempty"`
Include []string `json:"include,omitempty"`
Relations []RelationInfo `json:"relations,omitempty"`
}
func BuildQueryCriteria ¶ added in v0.1.0
func BuildQueryCriteria[T any](ctx Context, op CrudOperation, opts ...QueryBuilderOption) ([]repository.SelectCriteria, *Filters, error)
func BuildQueryCriteriaWithLogger ¶ added in v0.4.0
func BuildQueryCriteriaWithLogger[T any](ctx Context, op CrudOperation, logger Logger, enableTrace bool, opts ...QueryBuilderOption) ([]repository.SelectCriteria, *Filters, error)
type HookBatchFunc ¶ added in v0.5.0
type HookBatchFunc[T any] func(HookContext, []T) error
HookBatchFunc represents a lifecycle hook for multiple records.
func ChainBatchHooks ¶ added in v0.14.0
func ChainBatchHooks[T any](hooks ...HookBatchFunc[T]) HookBatchFunc[T]
ChainBatchHooks composes multiple batch hooks in order.
func HookBatchFromContext ¶ added in v0.12.0
func HookBatchFromContext[T any](hook func(Context, []T) error) HookBatchFunc[T]
HookBatchFromContext adapts a legacy batch hook (Context + []T) into the new HookBatchFunc form that receives HookContext metadata.
type HookContext ¶ added in v0.5.0
type HookContext struct {
Context Context
Metadata HookMetadata
Actor ActorContext
Scope ScopeFilter
RequestID string
CorrelationID string
// contains filtered or unexported fields
}
HookContext bundles the request context with hook metadata.
func (HookContext) ActivityHooks ¶ added in v0.13.0
func (h HookContext) ActivityHooks() *activity.Emitter
ActivityHooks returns the v2 activity emitter constructed from pkg/activity.
func (HookContext) HasNotificationEmitter ¶ added in v0.12.0
func (h HookContext) HasNotificationEmitter() bool
HasNotificationEmitter reports whether the controller configured a NotificationEmitter.
func (HookContext) NotificationEmitter ¶ added in v0.12.0
func (h HookContext) NotificationEmitter() NotificationEmitter
NotificationEmitter returns the configured NotificationEmitter (if any).
type HookFunc ¶ added in v0.5.0
type HookFunc[T any] func(HookContext, T) error
HookFunc represents a lifecycle hook for a single record.
func ChainHooks ¶ added in v0.14.0
ChainHooks composes multiple single-record hooks in order.
type HookMetadata ¶ added in v0.5.0
type HookMetadata struct {
Operation CrudOperation
Resource string
RouteName string
Method string
Path string
}
HookMetadata carries operational attributes for lifecycle hooks.
func HookMetadataFromContext ¶ added in v0.14.0
func HookMetadataFromContext(ctx context.Context) HookMetadata
HookMetadataFromContext retrieves hook metadata stored on the context.
type LifecycleHooks ¶ added in v0.5.0
type LifecycleHooks[T any] struct { BeforeCreate []HookFunc[T] AfterCreate []HookFunc[T] BeforeCreateBatch []HookBatchFunc[T] AfterCreateBatch []HookBatchFunc[T] BeforeUpdate []HookFunc[T] AfterUpdate []HookFunc[T] BeforeUpdateBatch []HookBatchFunc[T] AfterUpdateBatch []HookBatchFunc[T] AfterRead []HookFunc[T] AfterList []HookBatchFunc[T] BeforeDelete []HookFunc[T] AfterDelete []HookFunc[T] BeforeDeleteBatch []HookBatchFunc[T] AfterDeleteBatch []HookBatchFunc[T] }
LifecycleHooks groups all supported CRUD lifecycle hooks.
type MergePolicy ¶ added in v0.14.0
type MergePolicy struct {
PutReplace bool
PatchMerge bool
DeleteWithNull bool
// Per-field overrides keyed by source map name (e.g., "Metadata") and merge strategy ("deep", "shallow", "replace").
FieldMergeStrategy map[string]string
}
MergePolicy controls how partial updates are interpreted.
type MetadataRouterRouteInfo ¶ added in v0.4.0
type MetadataRouterRouteInfo interface {
RouterRouteInfo
Description(string) MetadataRouterRouteInfo
Summary(string) MetadataRouterRouteInfo
Tags(...string) MetadataRouterRouteInfo
Parameter(name, in string, required bool, schema map[string]any) MetadataRouterRouteInfo
RequestBody(desc string, required bool, content map[string]any) MetadataRouterRouteInfo
Response(code int, desc string, content map[string]any) MetadataRouterRouteInfo
}
MetadataRouterRouteInfo exposes optional metadata configuration methods
type NotFoundError ¶ added in v0.0.2
type NotFoundError struct {
// contains filtered or unexported fields
}
type NotificationEmitter ¶ added in v0.12.0
type NotificationEmitter interface {
SendNotification(ctx context.Context, event NotificationEvent) error
}
NotificationEmitter sends user-facing notifications derived from lifecycle events.
func NotificationEmitterFromContext ¶ added in v0.14.0
func NotificationEmitterFromContext(ctx context.Context) NotificationEmitter
NotificationEmitterFromContext extracts the notification emitter from the context.
type NotificationEvent ¶ added in v0.12.0
type NotificationEvent struct {
Operation CrudOperation
Phase ActivityPhase
Resource string
RouteName string
Method string
Path string
Actor ActorContext
Scope ScopeFilter
RequestID string
CorrelationID string
Records []any
Channel string
Template string
Recipients []string
Metadata map[string]any
}
NotificationEvent describes a notification occurrence.
type NotificationEventOption ¶ added in v0.12.0
type NotificationEventOption func(*NotificationEvent)
NotificationEventOption configures optional notification fields.
func WithNotificationChannel ¶ added in v0.12.0
func WithNotificationChannel(channel string) NotificationEventOption
WithNotificationChannel sets the outbound channel (e.g., email, webhook).
func WithNotificationMetadata ¶ added in v0.12.0
func WithNotificationMetadata(metadata map[string]any) NotificationEventOption
WithNotificationMetadata merges arbitrary metadata into the event.
func WithNotificationRecipients ¶ added in v0.12.0
func WithNotificationRecipients(recipients ...string) NotificationEventOption
WithNotificationRecipients declares the intended recipients (emails, IDs, etc.).
func WithNotificationTemplate ¶ added in v0.12.0
func WithNotificationTemplate(template string) NotificationEventOption
WithNotificationTemplate stores the downstream template identifier.
type Option ¶
type Option[T any] func(*Controller[T])
func WithActions ¶ added in v0.12.0
func WithActivityHooks ¶ added in v0.13.0
WithActivityHooks configures the controller with the shared activity emitter built from pkg/activity hooks and config. Defaults to no-op when hooks are empty.
func WithAdminMenuMetadata ¶ added in v0.12.0
func WithAdminMenuMetadata[T any](meta AdminMenuMetadata) Option[T]
func WithAdminScopeMetadata ¶ added in v0.12.0
func WithAdminScopeMetadata[T any](meta AdminScopeMetadata) Option[T]
func WithBatchReturnOrderByID ¶ added in v0.16.0
WithBatchReturnOrderByID enables ordered batch returns for CreateBatch/UpdateBatch.
func WithBatchRouteSegment ¶ added in v0.16.0
WithBatchRouteSegment sets the path segment used for batch routes (default "batch").
func WithCommandService ¶ added in v0.12.0
func WithCommandService[T any](factory CommandServiceFactory[T]) Option[T]
WithCommandService composes the default repository-backed service with the provided command adapter factory. When the factory is nil the option is a no-op.
func WithDeserializer ¶
func WithDeserializer[T any](d func(CrudOperation, Context) (T, error)) Option[T]
WithDeserializer sets a custom deserializer for the Controller.
func WithErrorEncoder ¶ added in v0.12.0
func WithErrorEncoder[T any](encoder ErrorEncoder) Option[T]
WithErrorEncoder overrides the encoder used when controllers serialize errors. When paired with the default response handler, this switches between the problem+json encoder and the legacy {success:false,error:string} payloads.
func WithFieldMapProvider ¶ added in v0.4.0
func WithFieldMapProvider[T any](provider FieldMapProvider) Option[T]
func WithFieldPolicyProvider ¶ added in v0.12.0
func WithFieldPolicyProvider[T any](provider FieldPolicyProvider[T]) Option[T]
func WithLifecycleHooks ¶ added in v0.5.0
func WithLifecycleHooks[T any](hooks LifecycleHooks[T]) Option[T]
func WithLogger ¶ added in v0.2.0
func WithNotificationEmitter ¶ added in v0.12.0
func WithNotificationEmitter[T any](emitter NotificationEmitter) Option[T]
func WithQueryLogging ¶ added in v0.4.0
func WithRelationFilter ¶ added in v0.8.0
func WithRelationFilter[T any](filter router.RelationFilterFunc) Option[T]
func WithRelationMetadataProvider ¶ added in v0.8.0
func WithRelationMetadataProvider[T any](provider router.RelationMetadataProvider) Option[T]
func WithResponseHandler ¶ added in v0.0.2
func WithResponseHandler[T any](handler ResponseHandler[T]) Option[T]
func WithRouteConfig ¶ added in v0.5.0
func WithRouteConfig[T any](config RouteConfig) Option[T]
func WithRowFilterHints ¶ added in v0.12.0
func WithRowFilterHints[T any](hints ...RowFilterHint) Option[T]
func WithScopeGuard ¶ added in v0.12.0
func WithScopeGuard[T any](guard ScopeGuardFunc[T]) Option[T]
func WithService ¶ added in v0.6.0
func WithServiceFuncs ¶ added in v0.6.0
func WithServiceFuncs[T any](overrides ServiceFuncs[T]) Option[T]
func WithVirtualFields ¶ added in v0.14.0
func WithVirtualFields[T any](cfg ...VirtualFieldHandlerConfig) Option[T]
WithVirtualFields enables virtual field handling with optional config.
type QueryBuilderOption ¶ added in v0.12.0
type QueryBuilderOption func(*queryBuilderConfig)
func WithAllowedFields ¶ added in v0.12.0
func WithAllowedFields(fields map[string]string) QueryBuilderOption
type RelationFilter ¶ added in v0.1.0
type RelationInfo ¶ added in v0.1.0
type RelationInfo struct {
Name string `json:"name"`
Filters []RelationFilter `json:"filters,omitempty"`
}
type RepositoryServiceOptions ¶ added in v0.16.0
type RepositoryServiceOptions struct {
BatchInsertCriteria []repository.InsertCriteria
BatchUpdateCriteria []repository.UpdateCriteria
}
RepositoryServiceOptions configures repository-backed service behavior.
type Request ¶ added in v0.1.0
type Request interface {
UserContext() context.Context
Params(key string, defaultValue ...string) string
BodyParser(out any) error
Query(key string, defaultValue ...string) string
QueryValues(key string) []string
QueryInt(key string, defaultValue ...int) int
Queries() map[string]string
Body() []byte
}
type ResourceController ¶ added in v0.1.0
ResourceController defines an interface for registering CRUD routes
type ResourceHandler ¶ added in v0.1.0
type ResponseHandler ¶ added in v0.0.2
type ResponseHandler[T any] interface { OnError(ctx Context, err error, op CrudOperation) error OnData(ctx Context, data T, op CrudOperation, filters ...*Filters) error OnEmpty(ctx Context, op CrudOperation) error OnList(ctx Context, data []T, op CrudOperation, filters *Filters) error }
ResponseHandler defines how controller responses are handled
func NewDefaultResponseHandler ¶ added in v0.0.2
func NewDefaultResponseHandler[T any]() ResponseHandler[T]
type RouteConfig ¶ added in v0.5.0
type RouteConfig struct {
Operations map[CrudOperation]RouteOptions
}
func DefaultRouteConfig ¶ added in v0.5.0
func DefaultRouteConfig() RouteConfig
type RouteOptions ¶ added in v0.5.0
type Router ¶ added in v0.1.0
type Router interface {
Get(path string, handler func(Context) error) RouterRouteInfo
Post(path string, handler func(Context) error) RouterRouteInfo
Put(path string, handler func(Context) error) RouterRouteInfo
Patch(path string, handler func(Context) error) RouterRouteInfo
Delete(path string, handler func(Context) error) RouterRouteInfo
}
Router is a simplified interface from the crud package perspective, referencing the generic router
func NewFiberAdapter ¶ added in v0.1.0
NewFiberAdapter creates a new crud.Router that uses a router.Router[any]
type RouterRouteInfo ¶ added in v0.1.0
type RouterRouteInfo interface {
Name(string) RouterRouteInfo
}
RouterRouteInfo is a simplified interface for route info
type RowFilterHint ¶ added in v0.12.0
type RowFilterHint struct {
Field string `json:"field"`
Operator string `json:"operator,omitempty"`
Description string `json:"description,omitempty"`
}
RowFilterHint documents guard/policy criteria applied to the resource.
type SchemaEntry ¶ added in v0.12.0
type SchemaEntry struct {
Resource string `json:"resource"`
Plural string `json:"plural"`
Document map[string]any `json:"document"`
UpdatedAt time.Time `json:"updated_at"`
}
SchemaEntry holds the cached OpenAPI document for a controller.
func GetSchema ¶ added in v0.12.0
func GetSchema(resource string) (SchemaEntry, bool)
GetSchema retrieves the schema for the given resource name.
func ListSchemas ¶ added in v0.12.0
func ListSchemas() []SchemaEntry
ListSchemas returns all registered schema documents.
type SchemaListener ¶ added in v0.12.0
type SchemaListener func(SchemaEntry)
SchemaListener receives notifications whenever a schema entry changes.
type ScopeColumnFilter ¶ added in v0.12.0
ScopeColumnFilter captures a single column restriction enforced by the guard.
type ScopeFilter ¶ added in v0.12.0
type ScopeFilter struct {
// ColumnFilters expresses equality/IN restrictions (guard authoritative).
ColumnFilters []ScopeColumnFilter
// Bypass instructs controllers to skip automatic filter application.
// Guard implementations must set this explicitly; it never defaults to true.
Bypass bool
// Labels provide optional structured metadata for logging/auditing.
Labels map[string]string
// Raw stores arbitrary data that higher layers may need for observability.
Raw map[string]any
}
ScopeFilter describes the row-level restrictions returned by a guard. Controllers apply these filters before executing repository calls.
func ScopeFromContext ¶ added in v0.12.0
func ScopeFromContext(ctx context.Context) ScopeFilter
ScopeFromContext extracts the guard scope filter from the context.
func (*ScopeFilter) AddColumnFilter ¶ added in v0.12.0
func (sf *ScopeFilter) AddColumnFilter(column string, operator string, values ...string)
AddColumnFilter appends a new filter, ignoring empty columns/values.
func (ScopeFilter) HasFilters ¶ added in v0.12.0
func (sf ScopeFilter) HasFilters() bool
HasFilters reports whether the guard produced any column filters.
type ScopeGuardFunc ¶ added in v0.12.0
type ScopeGuardFunc[T any] func(ctx Context, op CrudOperation) (ActorContext, ScopeFilter, error)
ScopeGuardFunc resolves the actor + scope restrictions for a CRUD operation.
type Service ¶ added in v0.6.0
type Service[T any] interface { Create(ctx Context, record T) (T, error) CreateBatch(ctx Context, records []T) ([]T, error) Update(ctx Context, record T) (T, error) UpdateBatch(ctx Context, records []T) ([]T, error) Delete(ctx Context, record T) error DeleteBatch(ctx Context, records []T) error Index(ctx Context, criteria []repository.SelectCriteria) ([]T, int, error) Show(ctx Context, id string, criteria []repository.SelectCriteria) (T, error) }
Service defines pluggable CRUD behaviours that the controller can delegate to.
func ComposeService ¶ added in v0.6.0
func ComposeService[T any](defaults Service[T], funcs ServiceFuncs[T]) Service[T]
ComposeService returns a Service implementation that uses the given defaults and overrides any operation provided in funcs.
func NewRepositoryService ¶ added in v0.6.0
func NewRepositoryService[T any](repo repository.Repository[T]) Service[T]
NewRepositoryService returns a Service[T] that delegates to repository.Repository[T].
func NewRepositoryServiceWithOptions ¶ added in v0.16.0
func NewRepositoryServiceWithOptions[T any](repo repository.Repository[T], opts RepositoryServiceOptions) Service[T]
NewRepositoryServiceWithOptions returns a Service[T] that delegates to repository.Repository[T].
func NewService ¶ added in v0.14.0
func NewService[T any](cfg ServiceConfig[T]) Service[T]
NewService composes the repository-backed service with optional layers in the default order (inner → outer): repo → virtual fields → validation → hooks → scope guard → field policy → activity/notifications. Alternate orderings should be implemented as custom wrappers by callers.
func NewServiceFromFuncs ¶ added in v0.6.0
func NewServiceFromFuncs[T any](repo repository.Repository[T], funcs ServiceFuncs[T]) Service[T]
NewServiceFromFuncs builds a service backed by the repository and applying overrides.
type ServiceConfig ¶ added in v0.14.0
type ServiceConfig[T any] struct { Repository repository.Repository[T] Hooks LifecycleHooks[T] ScopeGuard ScopeGuardFunc[T] FieldPolicy FieldPolicyProvider[T] VirtualFields VirtualFieldProcessor[T] Validator ValidatorFunc[T] ActivityHooks activity.Hooks ActivityConfig activity.Config NotificationEmitter NotificationEmitter ResourceName string ResourceType reflect.Type BatchReturnOrderByID bool }
ServiceConfig holds all optional business logic layers applied by NewService. ResourceName/ResourceType help field policies resolve friendly names when reflection on the model type is not sufficient or needs overriding.
type ServiceFuncs ¶ added in v0.6.0
type ServiceFuncs[T any] struct { Create func(ctx Context, record T) (T, error) CreateBatch func(ctx Context, records []T) ([]T, error) Update func(ctx Context, record T) (T, error) UpdateBatch func(ctx Context, records []T) ([]T, error) Delete func(ctx Context, record T) error DeleteBatch func(ctx Context, records []T) error Index func(ctx Context, criteria []repository.SelectCriteria) ([]T, int, error) Show func(ctx Context, id string, criteria []repository.SelectCriteria) (T, error) }
ServiceFuncs allows callers to override specific service operations.
type ValidationError ¶ added in v0.0.2
type ValidationError struct {
// contains filtered or unexported fields
}
type ValidatorFunc ¶ added in v0.14.0
ValidatorFunc validates a single record before persistence/update.
type VirtualFieldDef ¶ added in v0.14.0
type VirtualFieldDef struct {
FieldName string
JSONName string
SourceField string
FieldType reflect.Type
FieldIndex int
AllowZero bool
MergeStrategy string // e.g. deep|shallow|replace (used by service merge semantics)
}
VirtualFieldDef describes a virtual field extracted from struct tags.
type VirtualFieldHandler ¶ added in v0.14.0
type VirtualFieldHandler[T any] struct { // contains filtered or unexported fields }
VirtualFieldHandler moves virtual fields into/out of a map field (e.g. metadata).
func NewVirtualFieldHandler ¶ added in v0.14.0
func NewVirtualFieldHandler[T any]() *VirtualFieldHandler[T]
NewVirtualFieldHandler builds a handler using defaults.
func NewVirtualFieldHandlerWithConfig ¶ added in v0.14.0
func NewVirtualFieldHandlerWithConfig[T any](cfg VirtualFieldHandlerConfig) *VirtualFieldHandler[T]
NewVirtualFieldHandlerWithConfig builds a handler with custom config.
func (*VirtualFieldHandler[T]) AfterLoad ¶ added in v0.14.0
func (h *VirtualFieldHandler[T]) AfterLoad(ctx HookContext, model T) error
AfterLoad hydrates virtual fields from the backing map, preserving or removing keys based on config.
func (*VirtualFieldHandler[T]) AfterLoadBatch ¶ added in v0.14.0
func (h *VirtualFieldHandler[T]) AfterLoadBatch(ctx HookContext, models []T) error
AfterLoadBatch hydrates virtuals for a slice of models.
func (*VirtualFieldHandler[T]) BeforeSave ¶ added in v0.14.0
func (h *VirtualFieldHandler[T]) BeforeSave(ctx HookContext, model T) error
BeforeSave moves virtual values into the backing map and optionally clears the fields.
func (*VirtualFieldHandler[T]) FieldDefs ¶ added in v0.14.0
func (h *VirtualFieldHandler[T]) FieldDefs() []VirtualFieldDef
FieldDefs returns a copy of detected virtual field definitions.
type VirtualFieldHandlerConfig ¶ added in v0.14.0
type VirtualFieldHandlerConfig struct {
PreserveVirtualKeys *bool // keep virtual keys in the backing map after load (default: true)
CopyMetadata bool // defensive copy of map before mutation
ClearVirtualValues *bool // clear virtual field after BeforeSave (default: true)
AllowZeroTag string // tag option name to opt-in zero moves for value fields
Dialect string // virtual field SQL dialect (default: postgres)
}
VirtualFieldHandlerConfig controls extraction/injection behavior.
type VirtualFieldProcessor ¶ added in v0.14.0
type VirtualFieldProcessor[T any] interface { BeforeSave(HookContext, T) error AfterLoad(HookContext, T) error AfterLoadBatch(HookContext, []T) error }
VirtualFieldProcessor is implemented by VirtualFieldHandler and test doubles.
Source Files
¶
- actions.go
- admin_metadata.go
- controller.go
- crud.go
- error_encoder.go
- fiber_adapter.go
- field_policy.go
- hooks.go
- logger.go
- merge_virtual.go
- notification.go
- openapi_meta.go
- options.go
- pagination.go
- query.go
- query_config.go
- relation_descriptor.go
- request_context.go
- response.go
- router_adapter.go
- schema_helpers.go
- schema_registry.go
- scope_guard.go
- service.go
- service_factory.go
- virtual_field_map_provider.go
- virtual_fields.go
- virtual_fields_openapi.go
- virtual_query.go