rest

package module
v0.0.0-...-8e6d5bb Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2025 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultPage     = 1
	DefaultPageSize = 10
)

Variables

View Source
var (
	ErrNoValidatorEngine = errors.New("no validator engine found")
)

Functions

func AbortRequest

func AbortRequest(ctx *gin.Context, errs ...error)

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

func AddClauses(stmt *gorm.Statement, clauses []clause.Interface)

AddClauses adds multiple clauses to a GORM database statement.

func AfterBindHook

func AfterBindHook(ctx *gin.Context, entity any) (aborted bool)

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

func BeforeBindHook(ctx *gin.Context, entity any) (aborted bool)

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

func BeforeRenderHook(ctx *gin.Context, entity any) (aborted bool)

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

func BindID(ctx *gin.Context, entity any) (aborted bool)

BindID sets the ID of the entity if it implements types.IModel and the ResourceID is present in the URL parameters.

func BindJSON

func BindJSON(ctx *gin.Context, entity any) (aborted bool)

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

func CamelToSnake(s string) string

CamelToSnake converts a camel case string to a snake case string.

func HandleError

func HandleError(ctx *gin.Context, err error) bool

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 IsLetter

func IsLetter(s string) bool

IsLetter checks if the given string consists entirely of letter characters.

func ModelFactory

func ModelFactory(data any) any

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

func ParseAcceptHeader(acceptHeader string) []string

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

func ParseListOptions(ctx *gin.Context, entity any) (err error)

ParseListOptions parses the list options from the query parameters and sets them in the context.

func RegisterValidation

func RegisterValidation(tag string, fn validator.Func) error

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) Create

func (r *BaseView) Create(ctx *gin.Context, entity any) types.IRender

Create handles the creation of a new entity and returns a render object.

func (*BaseView) Delete

func (r *BaseView) Delete(ctx *gin.Context, entity any) types.IRender

Delete handles deleting an entity and returns a render object.

func (*BaseView) List

func (r *BaseView) List(ctx *gin.Context, entities any) types.IRender

List handles listing entities and returns a render object.

func (*BaseView) Read

func (r *BaseView) Read(ctx *gin.Context, entity any) types.IRender

Read handles reading an entity and returns a render object.

func (*BaseView) SetResource

func (r *BaseView) SetResource(resource types.IResource)

SetResource sets the resource for this view.

func (*BaseView) SupportedMimeTypes

func (r *BaseView) SupportedMimeTypes() map[string]any

SupportedMimeTypes returns a pointer to the set of supported MIME types.

func (*BaseView) Update

func (r *BaseView) Update(ctx *gin.Context, entity any) types.IRender

Update handles updating an entity and returns a render object.

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.

func (*DatabaseService) Update

func (r *DatabaseService) Update(ctx *gin.Context, entity any) (err error)

Update updates an existing entity in the database.

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

func (r *Model) BeforeCreate(_ *gorm.DB) error

BeforeCreate is a GORM hook that generates a UUID for the Model's ID field if it is not already set.

func (*Model) GetID

func (r *Model) GetID() string

GetID returns the unique identifier of the model.

func (*Model) SetID

func (r *Model) SetID(id string)

SetID sets the unique identifier for the model.

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.

func (*REST) Register

func (r *REST) Register(resource types.IResource)

Register adds a new resource to the REST API, setting up its routes and dependencies.

Directories

Path Synopsis
view

Jump to

Keyboard shortcuts

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