The entity is the object that we interested in database
The fundamental entity
The base entity is contains the essential attributes that entity should have
type Base struct {
ID *uuid.UUID `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"created_at" gorm:"type:timestamp;autoCreateTime:nano"`
UpdatedAt time.Time `json:"updated_at" gorm:"type:timestamp;autoUpdateTime:nano"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index;type:timestamp"`
}
The Base
entity will create new uuid everytime when save to database if the id is blank
func (b *Base) BeforeCreate(_ *gorm.DB) error {
if b.ID == nil {
b.ID = UUIDAdr(uuid.New())
}
return nil
}
When you want to define new entity you need to embed this entity
type NewEntity struct{
repositorysdk.Base
// other fields
}
The entity for collect the metadata of pagination
The metadata of pagination
type PaginationMetadata struct {
ItemsPerPage int
ItemCount int
TotalItem int
CurrentPage int
TotalPage int
}
The method for get the offset value
offset := meta.GetOffset()
name | description | example |
---|---|---|
offset | the offset value (calculate from ItemPerPage value and CurrentPage value) | 10 |
The method for get the item per page value
itemPerPage := meta.GetItemPerPage()
name | description | example |
---|---|---|
itemPerPage | the item per page value (min: 10, max: 100) | 10 |
The method for get the current page value
currentPage := meta.GetItemPerPage()
name | description | example |
---|---|---|
currentPage | the current page value (min: 1) | 1 |
Convert to proto type
metaProto := meta.ToProto()
name | description | example |
---|---|---|
metaProto | metadata in *pb.PaginationMetadata |
Data Transfer Object is the object use for represent the attribute between the service
The base query result entity for opensearch
The base entity is contains the essential attributes that entity should have
type QueryResult struct {
Took uint `json:"took"`
Timeout bool `json:"timeout"`
Shards Shard `json:"_shards"`
}
When you want to define new entity you need to embed this entity
type NewQueryResult struct{
gosdk.QueryResult
// other fields
}
The stats of shards
The value of the statistic of shard
type Shard struct {
Total uint `json:"total"`
Successful uint `json:"successful"`
Skipped uint `json:"skipped"`
Failed uint `json:"failed"`
}
Gorm repository is the instance that has the code set for simple use case of gorm and can be extends by insert the scope
return *gorm.DB
when successfully
db, err := repositorysdk.InitDatabase(PostgresDatabaseConfig, Debug)
if err != nil {
// handle error
}
Parameters
name | description |
---|---|
Postgres Database Config | Postgres config |
Debug | Enable debug mode |
Configuration
type PostgresDatabaseConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"username"`
Password string `mapstructure:"password"`
Name string `mapstructure:"name"`
SSL string `mapstructure:"ssl"`
}
name | description | example |
---|---|---|
Host | Hostname of the postgres | localhost |
Port | Port of database | 5432 |
User | Postgres username | postgres |
Password | Postgres password | root |
Name | The database name | postgres |
SSL | SSL mode | disable |
repo := repositotysdk.NewGormRepository(*GormDB)
name | description |
---|---|
Gorm DB | the client of the gorm |
name | description | example |
---|---|---|
repo | the gorm repository instance |
type Entity interface {
TableName() string
}
name | description |
---|---|
TableName() | name of the table of the entity |
the gorm scope for pagination query
if err := r.db.GetDB().
Scopes(repositotysdk.Pagination[Entity](entityList, metadata, gormDB, ...Scope)).
Find(&entityList).
Error; err != nil {
return err
}
metadata.ItemCount = len(*entityList)
metadata.CalItemPerPage()
return nil
name | description | example |
---|---|---|
entityList | list of entities | |
metadata | pagination metadata | |
gormDB | gorm client | |
Scope | extends scope (optional) |
Example Basic
if err := r.db.GetDB().
Scopes(repositotysdk.Pagination[Entity](entity, metadata, r.db.GetDB())).
Find(&entity).
Error; err != nil {
return err
}
metadata.ItemCount = len(*entity)
metadata.CalItemPerPage()
return nil
Example with Scope
if err := r.db.GetDB().
Preload("Relationship")
Scopes(repositotysdk.Pagination[Entity](entity, metadata, r.db.GetDB(), func(db *gorm.DB) *gorm.DB{
return db.Where("something = ?", something)
})).
Find(&entity, "something = ?", something).
Error; err != nil {
return err
}
metadata.ItemCount = len(*entity)
metadata.CalItemPerPage()
return nil
return the gorm db instance
db = gorm.GetDB()
name | description | example |
---|---|---|
gormDB | gorm client |
findAll with pagination
var entityList []Entity
if err := repo.FindOne(metadata, &entityList, ...scope); err != nil{
// handle error
}
name | description | example |
---|---|---|
entityList | list of entities | |
metadata | pagination metadata | |
Scope | extends scope (optional) |
findOne entity
entity := Entity{}
if err := repo.FindOne(id, &entity, ...scope); err != nil{
// handle error
}
name | description | example |
---|---|---|
id | id of entity | |
entity | empty entity for receive data | |
Scope | extends scope (optional) |
Example with Scope
if err := repo.FindOne(id, &entity, func(db *gorm.DB)*gorm.DB{
return db.Preload("Relationship").Where("something = ?")
}).
Error; err != nil {
return err
}
create entity
entity := Entity{}
if err := repo.Create(&entity, ...scope); err != nil{
// handle error
}
name | description | example |
---|---|---|
entity | entity with data | |
Scope | extends scope (optional) |
update entity
entity := Entity{}
if err := repo.Update(id, &entity, ...scope); err != nil{
// handle error
}
name | description | example |
---|---|---|
id | id of entity | |
entity | entity with data | |
Scope | extends scope (optional) |
delete entity
entity := Entity{}
if err := repo.Delete(id, &entity, ...scope); err != nil{
// handle error
}
name | description | example |
---|---|---|
id | id of entity | |
entity | entity with data | |
Scope | extends scope (optional) |
Redis repository is the repository interface for using redis work on-top of go-redis
return *redis.Client
when successfully
cache, err := gosdk.InitRedisConnect(RedisConfig)
if err != nil {
// handle error
}
Parameters
name | description |
---|---|
Redis Config | Redis config |
Configuration
type RedisConfig struct {
Host string `mapstructure:"host"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
}
name | description | example |
---|---|---|
Host | The host of the redis in format hostname:port |
localhost:6379 |
Password | Redis password | password |
DB | The database number | 0 |
Redis repository can be initialized by NewRedisRepository method
repo := repositorysdk.NewRedisRepository(*RedisClient)
name | description |
---|---|
Redis Client | the client of the redis for calling an API |
name | description | example |
---|---|---|
repo | the redis repository instance |
if err := repo.SaveCache(key, value, ttl); err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"key" |
value | value of cache (any type) | "value", 1, &struct{}{} |
ttl | expiration time of cache | 3600 |
if err := repo.SaveHashCache(key, field, value, ttl); err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"user" |
field | field of hash cache (must be string ) |
"name" |
value | value of hash cache (must be string ) |
"alice" |
ttl | expiration time of cache | 3600 |
if err := repo.SaveAllHashCache(key, value, ttl); err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"user" |
value | map of hash cache (must be map[string]string ) |
map[string]string{"name": "alice"} |
ttl | expiration time of cache | 3600 |
type User struct{
name string
}
result := User{}
if err := repo.GetCache(key, &result); err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"user" |
result | the result point struct{} for receive the cache |
value ,err := repo.GetHashCache(key, field)
if err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"user" |
field | field of hash cache (must be string ) |
"name" |
name | description | example |
---|---|---|
value | value of cache in string |
"alice" |
values ,err := repo.GetAllHashCache(key, field)
if err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"user" |
field | field of hash cache (must be string ) |
"name" |
name | description | example |
---|---|---|
values | values of cache in map[string]string |
map[string]string{"name":"alice"} |
if err := repo.RemoveCache(key); err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"key" |
if err := repo.SetExpire(key, ttl); err != nil{
// handle error
}
name | description | example |
---|---|---|
key | key of cache (must be string ) |
"key" |
ttl | expiration time of cache | 3600 |