model

package
v0.0.62 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2024 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package model provides ...

Index

Constants

View Source
const (
	LoginStatusSuccess = "success"
	LoginStatusFailure = "failure"
)

Variables

View Source
var (
	// Records is the table records must be pr-eexists before any database curd,
	// its register by register function.
	// The underlying type of map value must be model pointer to structure, eg: *model.User
	//
	// Records is the table records that should created automatically when app bootstraping.
	Records []*Record = make([]*Record, 0)

	// Tables is the database table that should created automatically when app bootstraping.
	Tables []types.Model

	TablesWithDB []struct {
		Table  types.Model
		DBName string
	}

	// Routes is a map slice that element is map[string][]Verb
	// The map key is the route path, eg: '/asset' or 'asset'
	//   or '/api/asset' (the prefiex /api will be remove automatically).
	// The map value is the Verb slice.
	// - VerbCreate is equivalent to http method "POST".
	// - VerbDelete is equivalent to http method "DELETE".
	// - VerbUpdate is equivalent to http method "PUT".
	// - VerbUpdatePartial is equivalent to http method "PATCH".
	// - VerbList is equivalent to http method "GET /xxx".
	// - VerbGET is equivalent to http method "GET /xxx/:id".
	// - VerbExport is equivalent to http method "GET" but specifially used to export resources.
	// - VerbImport is equivalent to http method "POST" but specifically used to import resources.
	Routes []route = make([]route, 0)
)
View Source
var (
	RootId      = "root"
	RootName    = "root"
	UnknownId   = "unknown"
	UnknownName = "未知"
	NoneId      = "none"
	NoneName    = "无"

	KeyName = "name"
	KeyId   = "id"
)
View Source
var ErrMobileLength = errors.New("mobile number length must be 11")

Functions

func Register

func Register[M types.Model](records ...M)

Register table with records and it will be created in database before any curd..

func RegisterRoutes

func RegisterRoutes[M types.Model](path string, verbs ...Verb)

RegisterRoutes register one route path with multiple api verbs. call this function multiple to register multiple route path. If route path is same, using latest register route path.

func RegisterTo

func RegisterTo[M types.Model](dbname string, records ...M)

RegisterTo same as Register but with custom database instances. dbname should always lowercase.

func SetID

func SetID(m types.Model, id ...string)

Types

type Base

type Base struct {
	ID string `json:"id" gorm:"primaryKey" schema:"id"`

	CreatedBy      string    `json:"created_by,omitempty" schema:"created_by" gorm:"index"`
	UpdatedBy      string    `json:"updated_by,omitempty" schema:"updated_by" gorm:"index"`
	CreatedAt      time.Time `json:"created_at,omitempty" schema:"-" gorm:"index"`
	UpdatedAt      time.Time `json:"updated_at,omitempty" schema:"-" gorm:"index"`
	Remark         *string   `json:"remark,omitempty" gorm:"size:10240" schema:"-"` // 如果需要支持 PATCH 更新,则必须是指针类型
	Order          *uint     `json:"order,omitempty" schema:"-"`
	Error          string    `json:"error,omitempty" schema:"-"`
	InternalRemark string    `json:"internal_remark,omitempty" schema:"-"` // 内部系统的备注

	// Query parameter
	Page       uint    `json:"-" gorm:"-" schema:"page"`         // Query parameter, eg: "page=2"
	Size       uint    `json:"-" gorm:"-" schema:"size"`         // Query parameter, eg: "size=10"
	Expand     *string `json:"-" gorm:"-" schema:"_expand"`      // Query parameter, eg: "_expand=children,parent".
	Depth      *uint   `json:"-" gorm:"-" schema:"_depth"`       // Query parameter, eg: "_depth=3".
	Fuzzy      *bool   `json:"-" gorm:"-" schema:"_fuzzy"`       // Query parameter, eg: "_fuzzy=true"
	SortBy     string  `json:"-" gorm:"-" schema:"_sortby"`      // Query parameter, eg: "_sortby=name"
	NoCache    bool    `json:"-" gorm:"-" schema:"_nocache"`     // Query parameter: eg: "_nocache=false"
	ColumnName string  `json:"-" gorm:"-" schema:"_column_name"` // Query parameter: eg: "_column_name=created_at"
	StartTime  string  `json:"-" gorm:"-" schema:"_start_time"`  // Query parameter: eg: "_start_time=2024-04-29+23:59:59"
	EndTime    string  `json:"-" gorm:"-" schema:"_end_time"`    // Query parameter: eg: "_end_time=2024-04-29+23:59:59"
	Or         *bool   `json:"-" gorm:"-" schema:"_or"`          // query parameter: eg: "_or=true"
	Index      string  `json:"-" gorm:"-" schema:"_index"`       // Query parameter: eg: "_index=name"
	Select     string  `json:"-" gorm:"-" schema:"_select"`      // Query parameter: eg: "_select=field1,field2"

	gorm.Model `json:"-"`
}

Base implement types.Model interface. Each model must be expands the Base structure. You can implements your custom method to overwrite the defaults methods.

Usually, there are some gorm tags that may be of interest to you. gorm:"unique" gorm:"foreignKey:ParentID" gorm:"foreignKey:ParentID,references:ID"

func (*Base) CreateAfter

func (*Base) CreateAfter() error

func (*Base) CreateBefore

func (*Base) CreateBefore() error

These methods implement types.Hooker interface. model should create custom hook to overwrite default hooks.

func (*Base) DeleteAfter

func (*Base) DeleteAfter() error

func (*Base) DeleteBefore

func (*Base) DeleteBefore() error

func (*Base) Excludes

func (b *Base) Excludes() map[string][]any

func (*Base) Expands

func (b *Base) Expands() []string

func (*Base) GetAfter

func (*Base) GetAfter() error

func (*Base) GetBefore

func (*Base) GetBefore() error

func (*Base) GetCreatedAt

func (b *Base) GetCreatedAt() time.Time

func (*Base) GetCreatedBy

func (b *Base) GetCreatedBy() string

func (*Base) GetID

func (b *Base) GetID() string

func (*Base) GetTableName

func (b *Base) GetTableName() string

func (*Base) GetUpdatedAt

func (b *Base) GetUpdatedAt() time.Time

func (*Base) GetUpdatedBy

func (b *Base) GetUpdatedBy() string

func (*Base) ListAfter

func (*Base) ListAfter() error

func (*Base) ListBefore

func (*Base) ListBefore() error

func (*Base) MarshalLogObject

func (b *Base) MarshalLogObject(enc zapcore.ObjectEncoder) error

func (*Base) SetCreatedAt

func (b *Base) SetCreatedAt(t time.Time)

func (*Base) SetCreatedBy

func (b *Base) SetCreatedBy(s string)

func (*Base) SetID

func (b *Base) SetID(id ...string)

func (*Base) SetUpdatedAt

func (b *Base) SetUpdatedAt(t time.Time)

func (*Base) SetUpdatedBy

func (b *Base) SetUpdatedBy(s string)

func (*Base) UpdateAfter

func (*Base) UpdateAfter() error

func (*Base) UpdateBefore

func (*Base) UpdateBefore() error

func (*Base) UpdatePartialAfter

func (*Base) UpdatePartialAfter() error

func (*Base) UpdatePartialBefore

func (*Base) UpdatePartialBefore() error

type GormScanner

type GormScanner struct {
	Object any
}

func GormScannerWrapper

func GormScannerWrapper(object any) *GormScanner

GormScannerWrapper converts object to GormScanner that can be used in GORM. WARN: you must pass pointer to object.

func (*GormScanner) Scan

func (g *GormScanner) Scan(value any) (err error)

func (*GormScanner) Value

func (g *GormScanner) Value() (driver.Value, error)

type GormStrings

type GormStrings []string

func (*GormStrings) Scan

func (gs *GormStrings) Scan(value any) error

func (GormStrings) Value

func (gs GormStrings) Value() (driver.Value, error)

type GormTime

type GormTime time.Time

func (GormTime) MarshalJSON

func (ct GormTime) MarshalJSON() ([]byte, error)

func (*GormTime) Scan

func (t *GormTime) Scan(value any) error

func (*GormTime) UnmarshalJSON

func (t *GormTime) UnmarshalJSON(b []byte) error

func (GormTime) Value

func (t GormTime) Value() (driver.Value, error)

type LoginLog added in v0.0.42

type LoginLog struct {
	UserID   string      `json:"user_id" schema:"user_id"`
	Username string      `json:"username" schema:"username"`
	ClientIP string      `json:"client_ip" schema:"client_ip"`
	Token    string      `json:"token" schema:"token"`
	Status   LoginStatus `json:"status" schema:"status"`

	UserAgent
	Base
}

type LoginStatus added in v0.0.42

type LoginStatus string

type OperationLog

type OperationLog struct {
	User       string        `json:"user,omitempty" schema:"user"`   // 操作者, 本地账号该字段为空,例如 root
	IP         string        `json:"ip,omitempty" schema:"ip"`       // 操作者的 ip
	Op         OperationType `json:"op,omitempty" schema:"op"`       // 动作: 增删改查
	Table      string        `json:"table,omitempty" schema:"table"` // 操作了哪张表
	Model      string        `json:"model,omitempty" schema:"model"`
	RecordId   string        `json:"record_id,omitempty" schema:"record_id"`     // 表记录的 id
	RecordName string        `json:"record_name,omitempty" schema:"record_name"` // 表记录的 name
	Record     string        `json:"record,omitempty" schema:"record"`           // 记录全部内容
	OldRecord  string        `json:"old_record,omitempty"`                       // 更新前的内容
	NewRecord  string        `json:"new_record,omitempty"`                       // 更新后的内容
	Method     string        `json:"method,omitempty" schema:"method"`
	URI        string        `json:"uri,omitempty" schema:"uri"` // request uri
	UserAgent  string        `json:"user_agent,omitempty" schema:"user_agent"`
	RequestId  string        `json:"request_id,omitempty" schema:"request_id"`

	Base
}

type OperationType

type OperationType string
const (
	OperationTypeCreate        OperationType = "create"
	OperationTypeDelete        OperationType = "delete"
	OperationTypeUpdate        OperationType = "update"
	OperationTypeUpdatePartial OperationType = "update_partial"
	OperationTypeList          OperationType = "list"
	OperationTypeGet           OperationType = "get"
	OperationTypeExport        OperationType = "export"
	OperationTypeImport        OperationType = "import"
)

type Record

type Record struct {
	Table   types.Model
	Rows    any
	Expands []string
	DBName  string
}

Record is table record

type User

type User struct {
	Username     string `json:"username,omitempty" gorm:"unique" binding:"required"`
	Name         string `json:"name,omitempty"` // 等同于 username
	EnName       string `json:"en_name,omitempty"`
	Password     string `json:"password,omitempty"`
	RePassword   string `json:"re_password,omitempty" gorm:"-"`
	NewPassword  string `json:"new_password,omitempty" gorm:"-"`
	Email        string `json:"email,omitempty" gorm:"unique"`
	Avatar       string `json:"avatar,omitempty"`
	AvatarUrl    string `json:"avatar_url,omitempty"`    // 用户头像
	AvatarThumb  string `json:"avatar_thumb,omitempty"`  // 用户头像 72x72
	AvatarMiddle string `json:"avatar_middle,omitempty"` // 用户头像 240x240
	AvatarBig    string `json:"avatar_big,omitempty"`    // 用户头像 640x640
	Mobile       string `json:"mobile,omitempty"`
	Nickname     string `json:"nickname,omitempty"`
	Introduction string `json:"introduction,omitempty"`
	Status       uint   `json:"status,omitempty" gorm:"type:smallint;default:1;comment:status(0: disabled, 1: enabled)"`
	// State 员工状态
	// 1 在职
	// 2 离职
	// 3 试用期
	// 4 实习生
	RoleId       string `json:"role_id,omitempty"`
	DepartmentId string `json:"department_id,omitempty"`

	LastLogin  GormTime `json:"last_login,omitempty"`
	LockExpire int64    `json:"lock_expire,omitempty"`
	NumWrong   int      `json:"num_wrong,omitempty" gorm:"comment:the number of input password wrong"`

	Token           string   `json:"token,omitempty" gorm:"-"`
	AccessToken     string   `json:"access_token,omitempty" gorm:"-"`
	RefreshToken    string   `json:"refresh_token,omitempty" gorm:"-"`
	SessionId       string   `json:"session_id,omitempty" gorm:"-"`
	TokenExpiration GormTime `json:"token_expiration,omitempty"`

	Base
}

func (*User) CreateBefore

func (u *User) CreateBefore() error

CreateBefore check whether user mobile is valid.

func (*User) GetAfter

func (u *User) GetAfter() error

GetAfter clean the fields value of Password, RePassword, NewPassword .

func (*User) ListAfter

func (u *User) ListAfter() error

ListAfter clean the fields value of Password, RePassword, NewPassword .

type UserAgent added in v0.0.42

type UserAgent struct {
	Source   string `json:"source" schema:"source"`
	Platform string `json:"platform" schema:"platform"`
	Engine   string `json:"engine" schema:"engine"`
	Browser  string `json:"browser" schema:"browser"`
}

type UserInfo

type UserInfo struct {
	AccessToken      string `json:"access_token,omitempty"`       // user_access_token,用于获取用户资源
	TokenType        string `json:"token_type,omitempty"`         // token 类型
	ExpiresIn        int    `json:"expires_in,omitempty"`         // `access_token`的有效期,单位: 秒
	Name             string `json:"name,omitempty"`               // 用户姓名
	EnName           string `json:"en_name,omitempty"`            // 用户英文名称
	AvatarUrl        string `json:"avatar_url,omitempty"`         // 用户头像
	AvatarThumb      string `json:"avatar_thumb,omitempty"`       // 用户头像 72x72
	AvatarMiddle     string `json:"avatar_middle,omitempty"`      // 用户头像 240x240
	AvatarBig        string `json:"avatar_big,omitempty"`         // 用户头像 640x640
	OpenId           string `json:"open_id,omitempty"`            // 用户在应用内的唯一标识
	UnionId          string `json:"union_id,omitempty"`           // 用户统一ID
	Email            string `json:"email,omitempty"`              // 用户邮箱
	EnterpriseEmail  string `json:"enterprise_email,omitempty"`   // 企业邮箱,请先确保已在管理后台启用飞书邮箱服务
	UserId           string `json:"user_id,omitempty"`            // 用户 user_id
	Mobile           string `json:"mobile,omitempty"`             // 用户手机号
	TenantKey        string `json:"tenant_key,omitempty"`         // 当前企业标识
	RefreshExpiresIn int    `json:"refresh_expires_in,omitempty"` // `refresh_token` 的有效期,单位: 秒
	RefreshToken     string `json:"refresh_token,omitempty"`      // 刷新用户 `access_token` 时使用的 token
	Sid              string `json:"sid,omitempty"`                // 用户当前登录态session的唯一标识,为空则不返回

	Base
}

func (*UserInfo) MarshalLogObject

func (u *UserInfo) MarshalLogObject(enc zapcore.ObjectEncoder) error

type Verb

type Verb string

Verb is router Verb

const (
	VerbCreate        Verb = "create"
	VerbDelete        Verb = "delete"
	VerbUpdate        Verb = "update"
	VerbUpdatePartial Verb = "update_partial"
	VerbList          Verb = "list"
	VerbGet           Verb = "get"
	VerbExport        Verb = "export"
	VerbImport        Verb = "import"

	// VerbMost includes verbs: `create`, `delete`, `update`, `update_partial`, `list`, `get`
	VerbMost Verb = "most"
	// VerbAll includes VerbGeneral, VerbImport, VerbExport
	VerbAll Verb = "all"
)

Jump to

Keyboard shortcuts

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