gocrud

package module
v0.0.0-...-545cf09 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2025 License: MIT Imports: 21 Imported by: 8

README

CRUD in Golang

Example

See gocrud_test.go

Documentation

Index

Constants

View Source
const (
	XFileDigest = "X-File-Digest"
)

Variables

View Source
var (
	NilGroupError      = errors.New("engine is nil")
	NilRepositoryError = errors.New("database is nil")
)
View Source
var (
	DefaultPageSizes = []int64{10, 20, 50, 100}
	DefaultPageSize  = DefaultPageSizes[0]
)
View Source
var (
	DefaultOkCodes       = []int{200}
	ErrorBaseURLRequired = errors.New("BaseURL is required")
)
View Source
var (
	ErrorIncompleteWrite    = errors.New("incomplete write")
	ErrorFileExists         = errors.New("file already exists")
	ErrorFileIsDir          = errors.New("file is a directory")
	ErrorUploadNotAllowed   = errors.New("upload not allowed")
	ErrorFileDigestMismatch = errors.New("digest mismatch")
)
View Source
var RestCoder = NewDefaultCoder()

Functions

func ContainsByBase

func ContainsByBase[T IBase](array []T, one T) bool

func ContainsByID

func ContainsByID[T IBase](array []T, id ID) bool

func DefaultCorsConfig

func DefaultCorsConfig() cors.Config

func MakeErrorResponse

func MakeErrorResponse(context *gin.Context, code Code, err any)

func MakeJSONRequest

func MakeJSONRequest[T any, RR any](crudy *Crudy[T], u *url.URL, method string, body io.Reader, res *R[RR]) error

func MapFuncOverCommaSeparatedString

func MapFuncOverCommaSeparatedString(mapFunc func(string), css string)

func New

func New[T any](group *gin.RouterGroup, database *gorm.DB, crud Crud[T]) error

func NewCors

func NewCors() gin.HandlerFunc

func NewHardDeleteHandler

func NewHardDeleteHandler[T any](coder Coder) func(context *gin.Context, db *gorm.DB) bool

func NewHttpFileSystem

func NewHttpFileSystem(group *gin.RouterGroup, folder string, config *HttpFileSystemConfig) error

func NewSingleHTMLServe

func NewSingleHTMLServe(group *gin.RouterGroup, indexHTMLFile string, config *SingleHTMLServeConfig) error

func NewSoftDeleteHandler

func NewSoftDeleteHandler[T any](coder Coder) func(context *gin.Context, db *gorm.DB) bool

func NowString

func NowString(pattern *string) string

func NumericValidate

func NumericValidate(value string) any

func OverflowedArrayTrimmer

func OverflowedArrayTrimmer[T any](array []T, max int) []T

func OverflowedArrayTrimmerFilter

func OverflowedArrayTrimmerFilter[T any](max int) func([]T) []T

func Pick

func Pick[T any](arr []T, index int, defaultValue T) T

func Pointer

func Pointer[T any](t T) *T

func RecoveryHandler

func RecoveryHandler(responseFullError bool) gin.HandlerFunc

func SaveAsDigestedFile

func SaveAsDigestedFile(
	folder string,
	filename string,
	reader io.Reader,
	length int64,
	validigest FileDigest,
) (Filename, FileDigest, error)

func StringArrayFromCommaSeparatedString

func StringArrayFromCommaSeparatedString(css string) []string

func Ternary

func Ternary[T any](condition bool, onTrue T, onFalse T) T

func ValuableArray

func ValuableArray(array []string) (bool, string)

func ValuableString

func ValuableString(str *string, ifEmptyValue string) string

func Wait4CtrlC

func Wait4CtrlC() os.Signal

Types

type Base

type Base struct {
	ID        ID         `json:"id"        gorm:"primaryKey"`
	CreatedAt time.Time  `json:"createdAt" gorm:"autoCreateTime;<-:create"`
	UpdatedAt time.Time  `json:"updatedAt" gorm:"autoUpdateTime"`
	DeletedAt *time.Time `json:"deletedAt"`
}

type Code

type Code string

type Coder

type Coder interface {
	OK() Code
	InternalServerError() Code
	BadRequest() Code
	NotFound() Code
	MethodNotAllowed() Code
	Conflict() Code

	From(code string) Code
	FromStatus(status int) Code
}

func NewDefaultCoder

func NewDefaultCoder() Coder

type Crud

type Crud[T any] struct {
	DisallowAnyPageSize bool
	DefaultPageSize     int64
	PageSizes           []int64

	SearchHandlers SearchHandlers

	EnableGetAll  bool
	DisableGetOne bool
	DisableCount  bool
	DisablePage   bool
	DisableSave   bool
	DisableDelete bool

	WillGetAll func(context *gin.Context, db *gorm.DB) *gorm.DB
	DidGetAll  func(records []T, context *gin.Context, db *gorm.DB)

	WillGetOne func(context *gin.Context, db *gorm.DB) *gorm.DB
	DidGetOne  func(record *T, context *gin.Context, db *gorm.DB)

	WillCount func(context *gin.Context, db *gorm.DB) *gorm.DB
	DidCount  func(count *int64, context *gin.Context, db *gorm.DB)

	WillPage func(pageNum *int64, pageSize *int64, context *gin.Context, db *gorm.DB) *gorm.DB
	DidPage  func(pageNum int64, pageSize int64, list []T, context *gin.Context, db *gorm.DB)

	WillSave func(record *T, context *gin.Context, db *gorm.DB)
	DidSave  func(record *T, context *gin.Context, db *gorm.DB)

	WillDelete func(context *gin.Context, db *gorm.DB)
	OnDelete   func(context *gin.Context, db *gorm.DB) bool
	DidDelete  func(context *gin.Context, db *gorm.DB)

	Coder             Coder
	MakeOkResponse    func(context *gin.Context, data any)
	MakeErrorResponse func(context *gin.Context, code Code, err error)

	GetCensors func(context *gin.Context, db *gorm.DB) ([]*censored.Censor, error)
	// contains filtered or unexported fields
}

func (*Crud[T]) Decensor

func (crud *Crud[T]) Decensor(context *gin.Context, db *gorm.DB, record *T) error

func (*Crud[T]) Docensor

func (crud *Crud[T]) Docensor(context *gin.Context, db *gorm.DB, record *T, encensor bool) error

func (*Crud[T]) Encensor

func (crud *Crud[T]) Encensor(context *gin.Context, db *gorm.DB, record *T) error

type Crudy

type Crudy[T any] struct {
	// contains filtered or unexported fields
}

func NewCrudy

func NewCrudy[T any](options ...CrudyOption[T]) (*Crudy[T], error)

func (*Crudy[T]) All

func (c *Crudy[T]) All(searchParams map[string]string) ([]T, error)

func (*Crudy[T]) BuildURL

func (c *Crudy[T]) BuildURL(uri string, searchParams map[string]string) (*url.URL, error)

func (*Crudy[T]) Count

func (c *Crudy[T]) Count(searchParams map[string]string) (uint64, error)

func (*Crudy[T]) Delete

func (c *Crudy[T]) Delete(id ID) (bool, error)

func (*Crudy[T]) One

func (c *Crudy[T]) One(id ID) (*T, error)

func (*Crudy[T]) Page

func (c *Crudy[T]) Page(current, size uint64, searchParams map[string]string) ([]T, error)

func (*Crudy[T]) Save

func (c *Crudy[T]) Save(t *T) (*T, error)

type CrudyBasicOptions

type CrudyBasicOptions[T any] struct {
	CrudyOption[T]
	BaseURL    string
	HttpClient *http.Client
	OkCodes    *[]int
}

func (CrudyBasicOptions[T]) Apply

func (b CrudyBasicOptions[T]) Apply(crudy *Crudy[T]) error

type CrudyOption

type CrudyOption[T any] interface {
	Apply(*Crudy[T]) error
}

type CrudyPageOptions

type CrudyPageOptions[T any] struct {
	CrudyOption[T]
	DefaultSize uint64
}

func (CrudyPageOptions[T]) Apply

func (b CrudyPageOptions[T]) Apply(crudy *Crudy[T]) error

type DefaultCoder

type DefaultCoder struct {
	Coder
}

func (*DefaultCoder) BadRequest

func (d *DefaultCoder) BadRequest() Code

func (*DefaultCoder) Conflict

func (d *DefaultCoder) Conflict() Code

func (*DefaultCoder) From

func (d *DefaultCoder) From(code string) Code

func (*DefaultCoder) FromStatus

func (d *DefaultCoder) FromStatus(status int) Code

func (*DefaultCoder) InternalServerError

func (d *DefaultCoder) InternalServerError() Code

func (*DefaultCoder) MethodNotAllowed

func (d *DefaultCoder) MethodNotAllowed() Code

func (*DefaultCoder) NotFound

func (d *DefaultCoder) NotFound() Code

func (*DefaultCoder) OK

func (d *DefaultCoder) OK() Code

type FileDigest

type FileDigest string

type Filename

type Filename string

type HttpFileSystemConfig

type HttpFileSystemConfig struct {
	AllowUpload    bool
	AllowOverwrite bool
	EnableDigest   bool // EnableDigest: if true, will save file with its digest, and discard client defined filename
	Coder          Coder
}

type IBase

type IBase interface {
	GetID() ID
}

type ID

type ID uint64

func IDsFromCommaSeparatedString

func IDsFromCommaSeparatedString(css string) []ID

type Operator

type Operator string
const (
	OperatorEqual      Operator = "="
	OperatorLike       Operator = "LIKE"
	OperatorNotLike    Operator = "NOT LIKE"
	OperatorIn         Operator = "IN"
	OperatorNotIn      Operator = "NOT IN"
	OperatorNull       Operator = "IS NULL"
	OperatorNNull      Operator = "IS NOT NULL"
	OperatorBetween    Operator = "BETWEEN"
	OperatorNotBetween Operator = "NOT BETWEEN"
	OperatorGt         Operator = ">"
	OperatorGte        Operator = ">="
	OperatorLt         Operator = "<"
	OperatorLte        Operator = "<="
	OperatorNeq        Operator = "!="
)

type R

type R[T any] struct {
	Code    Code   `json:"c"`
	Message string `json:"m"`
	Data    T      `json:"d"`
}

type SearchHandler

type SearchHandler = func(db *gorm.DB, values []string, with url.Values) *gorm.DB

func KeywordEqual

func KeywordEqual(name string, vt ValueTransformer[string, any]) SearchHandler

func KeywordIDIn

func KeywordIDIn(name string, vt ValueTransformer[[]ID, []ID]) SearchHandler

func KeywordIn

func KeywordIn(name string, vt ValueTransformer[[]string, []string]) SearchHandler

func KeywordLike

func KeywordLike(name string, vt ValueTransformer[string, any]) SearchHandler

func KeywordStatement

func KeywordStatement(name string, operator Operator, vt ValueTransformer[string, any]) SearchHandler

func NewSoftDeleteSearchHandler

func NewSoftDeleteSearchHandler(tableName string) SearchHandler

func SortBy

func SortBy(name string) SearchHandler

type SearchHandlers

type SearchHandlers = map[string]SearchHandler

type SingleHTMLServeConfig

type SingleHTMLServeConfig struct {
	AllowReplace bool
	Coder        Coder
}

type ValueTransformer

type ValueTransformer[T any, R any] func(value T) R

Jump to

Keyboard shortcuts

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