Categorygithub.com/PromptSnapshot/repositorysdk
modulepackage
1.3.4
Repository: https://github.com/promptsnapshot/repositorysdk.git
Documentation: pkg.go.dev

# README

Table of Contents

  1. Base Entity
  2. Base Dto
  3. Gorm Repository
  4. Redis Repository

About Entity

The entity is the object that we interested in database

Getting Start

Types

Base Entity

The fundamental entity

Structure

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"`
}

Hook

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
}

Usage

When you want to define new entity you need to embed this entity

type NewEntity struct{
	repositorysdk.Base
	// other fields
}

PaginationMetadata

The entity for collect the metadata of pagination

Structure

The metadata of pagination

type PaginationMetadata struct {
    ItemsPerPage int
    ItemCount    int
    TotalItem    int
    CurrentPage  int
    TotalPage    int
}

Methods

GetOffset

The method for get the offset value

offset := meta.GetOffset()

Return

namedescriptionexample
offsetthe offset value (calculate from ItemPerPage value and CurrentPage value)10
GetItemPerPage

The method for get the item per page value

itemPerPage := meta.GetItemPerPage()

Return

namedescriptionexample
itemPerPagethe item per page value (min: 10, max: 100)10
GetCurrentPage

The method for get the current page value

currentPage := meta.GetItemPerPage()

Return

namedescriptionexample
currentPagethe current page value (min: 1)1
ToProto

Convert to proto type

metaProto := meta.ToProto()

Return

namedescriptionexample
metaProtometadata in *pb.PaginationMetadata

About DTO

Data Transfer Object is the object use for represent the attribute between the service

Getting Start

Types

QueryResult

The base query result entity for opensearch

Structure

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"`
}

Usage

When you want to define new entity you need to embed this entity

type NewQueryResult struct{
	gosdk.QueryResult
	// other fields
}

Shard

The stats of shards

Structure

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"`
}

About Newbie Repository

Gorm repository is the instance that has the code set for simple use case of gorm and can be extends by insert the scope

Getting Start

Connection

PostgreSQL

return *gorm.DB when successfully

db, err := repositorysdk.InitDatabase(PostgresDatabaseConfig, Debug)
if err != nil {
    // handle error
}

Parameters

namedescription
Postgres Database ConfigPostgres config
DebugEnable 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"`
}
namedescriptionexample
HostHostname of the postgreslocalhost
PortPort of database5432
UserPostgres usernamepostgres
PasswordPostgres passwordroot
NameThe database namepostgres
SSLSSL modedisable

Initialize

repo := repositotysdk.NewGormRepository(*GormDB)

Configuration

Parameters

namedescription
Gorm DBthe client of the gorm

Return

namedescriptionexample
repothe gorm repository instance

Types

type Entity interface {
	TableName() string
}
namedescription
TableName()name of the table of the entity

Scopes

Pagination

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

Parameters

namedescriptionexample
entityListlist of entities
metadatapagination metadata
gormDBgorm client
Scopeextends 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

Usage

GetDB

return the gorm db instance

db = gorm.GetDB()

Returns

namedescriptionexample
gormDBgorm client

FindAll

findAll with pagination

var entityList []Entity

if err := repo.FindOne(metadata, &entityList, ...scope); err != nil{
	// handle error
}

Parameters

namedescriptionexample
entityListlist of entities
metadatapagination metadata
Scopeextends scope (optional)

FindOne

findOne entity

entity := Entity{}

if err := repo.FindOne(id, &entity, ...scope); err != nil{
	// handle error
}

Parameters

namedescriptionexample
idid of entity
entityempty entity for receive data
Scopeextends 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

create entity

entity := Entity{}

if err := repo.Create(&entity, ...scope); err != nil{
	// handle error
}

Parameters

namedescriptionexample
entityentity with data
Scopeextends scope (optional)

Create

update entity

entity := Entity{}

if err := repo.Update(id, &entity, ...scope); err != nil{
	// handle error
}

Parameters

namedescriptionexample
idid of entity
entityentity with data
Scopeextends scope (optional)

Delete

delete entity

entity := Entity{}

if err := repo.Delete(id, &entity, ...scope); err != nil{
	// handle error
}

Parameters

namedescriptionexample
idid of entity
entityentity with data
Scopeextends scope (optional)

About Redis Repository

Redis repository is the repository interface for using redis work on-top of go-redis

Getting Start

Connection

Redis

return *redis.Client when successfully

 cache, err := gosdk.InitRedisConnect(RedisConfig)
 if err != nil {
    // handle error
 }

Parameters

namedescription
Redis ConfigRedis config

Configuration

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}
namedescriptionexample
HostThe host of the redis in format hostname:portlocalhost:6379
PasswordRedis passwordpassword
DBThe database number0

Initialization

Redis repository can be initialized by NewRedisRepository method

repo := repositorysdk.NewRedisRepository(*RedisClient)

Configuration

Parameters

namedescription
Redis Clientthe client of the redis for calling an API

Return

namedescriptionexample
repothe redis repository instance

Usage

SaveCache

if err := repo.SaveCache(key, value, ttl); err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"key"
valuevalue of cache (any type)"value", 1, &struct{}{}
ttlexpiration time of cache3600

SaveHashCache

if err := repo.SaveHashCache(key, field, value, ttl); err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"user"
fieldfield of hash cache (must be string)"name"
valuevalue of hash cache (must be string)"alice"
ttlexpiration time of cache3600

SaveAllHashCache

if err := repo.SaveAllHashCache(key, value, ttl); err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"user"
valuemap of hash cache (must be map[string]string)map[string]string{"name": "alice"}
ttlexpiration time of cache3600

GetCache

type User struct{
	name string
}

result := User{}

if err := repo.GetCache(key, &result); err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"user"
resultthe result point struct{} for receive the cache

GetHashCache

value ,err := repo.GetHashCache(key, field)
if err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"user"
fieldfield of hash cache (must be string)"name"

Return

namedescriptionexample
valuevalue of cache in string"alice"

GetAllHashCache

values ,err := repo.GetAllHashCache(key, field)
if err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"user"
fieldfield of hash cache (must be string)"name"

Return

namedescriptionexample
valuesvalues of cache in map[string]stringmap[string]string{"name":"alice"}

RemoveCache

if err := repo.RemoveCache(key); err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"key"

SetExpire

if err := repo.SetExpire(key, ttl); err != nil{
    // handle error
}

Parameters

namedescriptionexample
keykey of cache (must be string)"key"
ttlexpiration time of cache3600

# Functions

DeleteWithoutResult returns a function that deletes the entity with the given ID using the given entity, but doesn't return the deleted entity.
DeleteWithResult returns a function that queries the entity with the given ID, deletes it, and returns the deleted entity.
FindOneByID returns a function that queries the entity with the given ID and returns the query result.
InitPostgresDatabase initializes a connection to a PostgreSQL database using the given configuration details.
InitRedisConnect initializes a connection to a Redis database using the given configuration details.
NewGormRepository function that create a new instance of gormRepository[T] with a GORM database connection.
No description provided by the author
Pagination returns a function that can be used as a GORM scope to paginate results.
UpdateByIDWithResult returns a function that updates the entity with the given ID using the given entity, and returns the updated entity.
UpdateWithoutResult returns a function that updates the entity with the given ID using the given entity, but doesn't return the updated entity.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author

# Structs

Base is a struct that holds common fields for database tables, including the ID, creation and update timestamps, and soft deletion timestamp.
BaseHardDelete is a struct that holds common fields for database tables, including the ID and creation and update timestamps, but excludes soft deletion timestamp.
PaginationMetadata is a struct that holds pagination metadata including the number of items per page, the current page, the total number of items, and the total number of pages.
PostgresDatabaseConfig is a struct that holds the configuration details required to establish a connection with a PostgreSQL database.
QueryResult is a struct that holds the result of an Opensearch query, including the time taken to execute the query, whether the query timed out, and information about the shards.
RedisConfig is a struct that holds the configuration details required to establish a connection with a Redis database.
Shard is a struct that holds information about the shards in an Opensearch cluster, including the total number of shards, the number of successful shards, the number of skipped shards, and the number of failed shards.

# Interfaces

No description provided by the author
No description provided by the author
No description provided by the author