Documentation
¶
Index ¶
- Constants
- Variables
- func AbortRequest(ctx *gin.Context, errs ...error)
- func AcceptMiddleware(supportedMimetypes map[string]any) gin.HandlerFunc
- func AddClauses(stmt *gorm.Statement, clauses []clause.Interface)
- func AfterBindHook(ctx *gin.Context, entity any) (aborted bool)
- func BeforeBindHook(ctx *gin.Context, entity any) (aborted bool)
- func BeforeRenderHook(ctx *gin.Context, entity any) (aborted bool)
- func BindID(ctx *gin.Context, entity any) (aborted bool)
- func BindJSON(ctx *gin.Context, entity any) (aborted bool)
- func CamelToSnake(s string) string
- func HandleError(ctx *gin.Context, err error) bool
- func InitializeValidators() error
- func IsLetter(s string) bool
- func ModelFactory(data any) any
- func ParseAcceptHeader(acceptHeader string) []string
- func ParseListOptions(ctx *gin.Context, entity any) (err error)
- func RegisterValidation(tag string, fn validator.Func) error
- type BaseController
- func (r *BaseController[T]) Create() gin.HandlerFunc
- func (r *BaseController[T]) Delete() gin.HandlerFunc
- func (r *BaseController[T]) List() gin.HandlerFunc
- func (r *BaseController[T]) Read() gin.HandlerFunc
- func (r *BaseController[T]) SetResource(resource types.IResource)
- func (r *BaseController[T]) Update() gin.HandlerFunc
- type BaseResource
- func (r *BaseResource) Controller() types.IController
- func (r *BaseResource) Name() string
- func (r *BaseResource) Register()
- func (r *BaseResource) Resource() types.IResourceGetter
- func (r *BaseResource) ResourceOf(name string) types.IResourceGetter
- func (r *BaseResource) Router() gin.IRouter
- func (r *BaseResource) Service() types.IService
- func (r *BaseResource) SetResources(resources *types.Resources)
- func (r *BaseResource) SetRouter(router gin.IRouter)
- func (r *BaseResource) View() types.IView
- type BaseView
- func (r *BaseView) Create(ctx *gin.Context, entity any) types.IRender
- func (r *BaseView) Delete(ctx *gin.Context, entity any) types.IRender
- func (r *BaseView) List(ctx *gin.Context, entities any) types.IRender
- func (r *BaseView) Read(ctx *gin.Context, entity any) types.IRender
- func (r *BaseView) SetResource(resource types.IResource)
- func (r *BaseView) SupportedMimeTypes() map[string]any
- func (r *BaseView) Update(ctx *gin.Context, entity any) types.IRender
- type DatabaseResource
- type DatabaseService
- func (r *DatabaseService) Create(ctx *gin.Context, entity any) (err error)
- func (r *DatabaseService) Delete(ctx *gin.Context, entity any) (err error)
- func (r *DatabaseService) List(ctx *gin.Context, entities any) (err error)
- func (r *DatabaseService) Read(ctx *gin.Context, entity any) (err error)
- func (r *DatabaseService) SetResource(resource types.IResource)
- func (r *DatabaseService) Update(ctx *gin.Context, entity any) (err error)
- type ListOptions
- type ListOptionsRequestParams
- type Model
- type REST
Constants ¶
const ( DefaultPage = 1 DefaultPageSize = 10 )
Variables ¶
var (
ErrNoValidatorEngine = errors.New("no validator engine found")
)
Functions ¶
func AbortRequest ¶
AbortRequest logs and aborts the request with the provided errors. It iterates over the errors, logs them to the context, and then aborts the request.
func AcceptMiddleware ¶
func AcceptMiddleware(supportedMimetypes map[string]any) gin.HandlerFunc
AcceptMiddleware is a Gin middleware that checks if the request's Accept header contains any of the supported MIME types. If no supported MIME type is found, it aborts the request with a ProblemUnsupportedMediaType error.
func AddClauses ¶
AddClauses adds multiple clauses to a GORM database statement.
func AfterBindHook ¶
AfterBindHook is a helper function that is executed by a controller after binding data to the entity. It checks if the entity implements the IModelAfterBind interface and calls its AfterBind method. If an error occurs, it handles the error using HandleError and returns true to abort further processing.
func BeforeBindHook ¶
BeforeBindHook is a helper function that is executed by a controller before binding data to the entity. It checks if the entity implements the IModelBeforeBind interface and calls its BeforeBind method. If an error occurs, it handles the error using HandleError and returns true to abort further processing.
func BeforeRenderHook ¶
BeforeRenderHook is a helper function that is executed by a controller before rendering the response. It checks if the entity implements the IModelBeforeRender interface and calls its BeforeRender method. If an error occurs, it handles the error using HandleError and returns true to abort further processing.
func BindID ¶
BindID sets the ID of the entity if it implements types.IModel and the ResourceID is present in the URL parameters.
func BindJSON ¶
BindJSON binds the JSON body of an HTTP request to the provided entity. It also handles before and after bind hooks, and error handling.
func CamelToSnake ¶
CamelToSnake converts a camel case string to a snake case string.
func HandleError ¶
HandleError handles common controller, service, and repository errors and maps them to appropriate HTTP responses. It checks the error type and calls AbortRequest with the corresponding problem.
func InitializeValidators ¶
func InitializeValidators() error
InitializeValidators create custom validators and registers them with the validation engine. It compiles the regex for sorting attributes and registers the validators with the engine.
func ModelFactory ¶
ModelFactory creates a new instance of the type represented by the provided data. It handles pointers, slices, and structs to return an appropriate new instance. This is useful for creating instances of models where you need to generate a new model object without knowing its specific type at compile time.
func ParseAcceptHeader ¶
ParseAcceptHeader parses the Accept header from an HTTP request. It returns a list of supported MIME types sorted by their quality weights in descending order.
func ParseListOptions ¶
ParseListOptions parses the list options from the query parameters and sets them in the context.
func RegisterValidation ¶
RegisterValidation registers a new validation function with the given tag. It returns an error if no validator engine is found or if the registration fails. This function can be used to add custom validations dynamically at runtime.
Types ¶
type BaseController ¶
type BaseController[T any] struct { types.IResourceGetter }
BaseController is a generic controller for handling CRUD operations on resources of type T.
func (*BaseController[T]) Create ¶
func (r *BaseController[T]) Create() gin.HandlerFunc
Create returns a gin.HandlerFunc that handles HTTP POST requests to create a new entity of type T.
func (*BaseController[T]) Delete ¶
func (r *BaseController[T]) Delete() gin.HandlerFunc
Delete returns a gin.HandlerFunc that handles HTTP DELETE requests to delete an entity of type T.
func (*BaseController[T]) List ¶
func (r *BaseController[T]) List() gin.HandlerFunc
List returns a gin.HandlerFunc that handles HTTP GET requests to list entities of type T.
func (*BaseController[T]) Read ¶
func (r *BaseController[T]) Read() gin.HandlerFunc
Read returns a gin.HandlerFunc that handles HTTP GET requests to read an entity of type T.
func (*BaseController[T]) SetResource ¶
func (r *BaseController[T]) SetResource(resource types.IResource)
SetResource sets the resource for this controller.
func (*BaseController[T]) Update ¶
func (r *BaseController[T]) Update() gin.HandlerFunc
Update returns a gin.HandlerFunc that handles HTTP PUT requests to update an entity of type T.
type BaseResource ¶
type BaseResource struct {
// contains filtered or unexported fields
}
BaseResource represents a RESTful resource with associated controller, service, and view.
func NewResource ¶
func NewResource[T any](controller types.IController, service types.IService, view types.IView) *BaseResource
NewResource creates a new BaseResource instance with the provided controller, service, and view.
func (*BaseResource) Controller ¶
func (r *BaseResource) Controller() types.IController
Controller returns the controller associated with the resource.
func (*BaseResource) Name ¶
func (r *BaseResource) Name() string
Name returns the snake_case name of the resource.
func (*BaseResource) Register ¶
func (r *BaseResource) Register()
Register sets up HTTP routes for the resource with appropriate authorization and controller methods.
func (*BaseResource) Resource ¶
func (r *BaseResource) Resource() types.IResourceGetter
Resource retrieves this resource from the Resources manager.
func (*BaseResource) ResourceOf ¶
func (r *BaseResource) ResourceOf(name string) types.IResourceGetter
ResourceOf retrieves a specific resource by name from the Resources manager.
func (*BaseResource) Router ¶
func (r *BaseResource) Router() gin.IRouter
Router returns the Gin router associated with the resource.
func (*BaseResource) Service ¶
func (r *BaseResource) Service() types.IService
Service returns the service associated with the resource.
func (*BaseResource) SetResources ¶
func (r *BaseResource) SetResources(resources *types.Resources)
SetResources assigns a Resources manager to the BaseResource.
func (*BaseResource) SetRouter ¶
func (r *BaseResource) SetRouter(router gin.IRouter)
SetRouter assigns a Gin router to the BaseResource for route registration.
func (*BaseResource) View ¶
func (r *BaseResource) View() types.IView
View returns the view associated with the resource.
type BaseView ¶
type BaseView struct { // IResourceGetter is an interface for getting resources. types.IResourceGetter // contains filtered or unexported fields }
BaseView is a struct that handles rendering of resources in different formats.
func (*BaseView) SetResource ¶
SetResource sets the resource for this view.
func (*BaseView) SupportedMimeTypes ¶
SupportedMimeTypes returns a pointer to the set of supported MIME types.
type DatabaseResource ¶
type DatabaseResource struct { // BaseResource is an embedded field representing the base resource functionalities. BaseResource // contains filtered or unexported fields }
DatabaseResource represents a resource that interacts with a database using GORM.
func NewDatabaseResource ¶
func NewDatabaseResource[T any](controller types.IController, service types.IService, view types.IView, database *gorm.DB) *DatabaseResource
NewDatabaseResource creates a new instance of DatabaseResource. It requires a controller, service, view, and a non-nil database connection.
func (*DatabaseResource) Database ¶
func (r *DatabaseResource) Database() *gorm.DB
Database returns the GORM DB instance associated with this resource.
type DatabaseService ¶
type DatabaseService struct { // IResourceDatabase is an embedded field that represents the resource database interface. types.IResourceDatabase }
DatabaseService provides methods to interact with the database using GORM and Gin.
func (*DatabaseService) Create ¶
func (r *DatabaseService) Create(ctx *gin.Context, entity any) (err error)
Create inserts a new entity into the database.
func (*DatabaseService) Delete ¶
func (r *DatabaseService) Delete(ctx *gin.Context, entity any) (err error)
Delete removes an entity from the database.
func (*DatabaseService) List ¶
func (r *DatabaseService) List(ctx *gin.Context, entities any) (err error)
List retrieves a list of entities from the database based on provided context and entity type.
func (*DatabaseService) Read ¶
func (r *DatabaseService) Read(ctx *gin.Context, entity any) (err error)
Read retrieves an entity from the database based on provided context and entity type.
func (*DatabaseService) SetResource ¶
func (r *DatabaseService) SetResource(resource types.IResource)
SetResource sets the resource for this service, ensuring it implements IResourceDatabase.
type ListOptions ¶
type ListOptions struct { Page int PageSize int Sorts *[]types.SortOption Filters *[]types.FilterOption }
ListOptions encapsulates the pagination, sorting, and filtering options for database queries.
func GetListOptions ¶
func GetListOptions(ctx *gin.Context) *ListOptions
GetListOptions retrieves pagination, sorting, and filtering options from the context.
func (*ListOptions) Filter ¶
func (r *ListOptions) Filter() clause.Interface
Filter returns a clause to filter the database result based on the provided filter options.
func (*ListOptions) Paginate ¶
func (r *ListOptions) Paginate() clause.Interface
Paginate returns a clause to paginate the database result.
func (*ListOptions) Sort ¶
func (r *ListOptions) Sort() clause.Interface
Sort returns a clause to sort the database result based on the provided sort options.
type ListOptionsRequestParams ¶
type ListOptionsRequestParams struct { Page int `form:"page[number]" binding:"omitempty,min=1"` PageSize int `form:"page[size]" binding:"omitempty,min=1,max=100"` Sort string `form:"sort" binding:"omitempty,sort_by_attributes"` }
ListOptionsRequestParams represents the query parameters for pagination, sorting, and filtering.
func (*ListOptionsRequestParams) FilterOptions ¶
func (*ListOptionsRequestParams) FilterOptions(ctx *gin.Context, entity any) *[]types.FilterOption
FilterOptions parses the filter parameters from the request and returns a slice of FilterOption. It validates the fields using the provided entity's filterable attributes.
func (*ListOptionsRequestParams) SortOptions ¶
func (r *ListOptionsRequestParams) SortOptions(ctx *gin.Context, entity any) *[]types.SortOption
SortOptions parses the sort parameters from the request and returns a slice of SortOption. It validates the fields using the provided entity's sortable attributes.
type Model ¶
type Model struct { // ID is the primary key of the Model, represented as a UUID string. // It can only be written once upon creation. ID string `json:"id,omitempty" yaml:"id,omitempty" xml:"id,omitempty" gorm:"type:uuid;primary_key;<-:create" binding:"omitempty"` // CreatedAt is a timestamp indicating when the Model was created. CreatedAt *null.Time `json:"created_at,omitempty" yaml:"created_at,omitempty" xml:"created_at,omitempty" gorm:"autoCreateTime" binding:"omitempty"` // UpdatedAt is a timestamp indicating when the Model was last updated. UpdatedAt *null.Time `json:"updated_at,omitempty" yaml:"updated_at,omitempty" xml:"updated_at,omitempty" gorm:"autoUpdateTime" binding:"omitempty"` // DeletedAt is a timestamp indicating when the Model was deleted, used for soft deletes. DeletedAt *types.DeletedAt `json:"deleted_at,omitempty" yaml:"deleted_at,omitempty" xml:"deleted_at,omitempty" gorm:"index" binding:"omitempty"` }
Model represents a base model with common fields for database records. To embed this base model into a model, consider following example:
type Book struct { types.Model `yaml:",inline"` Title string Author string }
func (*Model) BeforeCreate ¶
BeforeCreate is a GORM hook that generates a UUID for the Model's ID field if it is not already set.
type REST ¶
type REST struct {
// contains filtered or unexported fields
}
REST represents a RESTful API handler that manages resources and routes.
func New ¶
func New(router *gin.RouterGroup, jwtConfig *jwt.Config, authorizationConfig *authorization.Config) (rest *REST)
New creates a new instance of REST with the provided router, JWT configuration, and authorization configuration.