83 lines
2.5 KiB
Go
83 lines
2.5 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/Caknoooo/go-gin-clean-starter/database/entities"
|
|
"github.com/Caknoooo/go-gin-clean-starter/modules/mvendor/query"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type VendorRepository interface {
|
|
Create(ctx context.Context, tx *gorm.DB, vendor entities.MVendorEntity) (entities.MVendorEntity, error)
|
|
GetById(ctx context.Context, tx *gorm.DB, vendorId string) (entities.MVendorEntity, error)
|
|
GetAll(ctx context.Context, filter query.VendorFilter) ([]entities.MVendorEntity, int64, error)
|
|
Update(ctx context.Context, tx *gorm.DB, vendor entities.MVendorEntity) (entities.MVendorEntity, error)
|
|
Delete(ctx context.Context, tx *gorm.DB, vendorId string) error
|
|
}
|
|
|
|
type vendorRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewVendorRepository(db *gorm.DB) VendorRepository {
|
|
return &vendorRepository{db: db}
|
|
}
|
|
|
|
func (r *vendorRepository) Create(ctx context.Context, tx *gorm.DB, vendor entities.MVendorEntity) (entities.MVendorEntity, error) {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
if err := tx.WithContext(ctx).Create(&vendor).Error; err != nil {
|
|
return vendor, err
|
|
}
|
|
return vendor, nil
|
|
}
|
|
|
|
func (r *vendorRepository) GetById(ctx context.Context, tx *gorm.DB, vendorId string) (entities.MVendorEntity, error) {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
var vendor entities.MVendorEntity
|
|
if err := tx.WithContext(ctx).Preload("Client").First(&vendor, "id = ?", vendorId).Error; err != nil {
|
|
return vendor, err
|
|
}
|
|
return vendor, nil
|
|
}
|
|
|
|
func (r *vendorRepository) GetAll(ctx context.Context, filter query.VendorFilter) ([]entities.MVendorEntity, int64, error) {
|
|
var vendors []entities.MVendorEntity
|
|
var total int64
|
|
db := query.ApplyVendorFilters(r.db, filter)
|
|
db.Model(&entities.MVendorEntity{}).Count(&total)
|
|
if filter.PerPage > 0 && filter.Page > 0 {
|
|
db = db.Limit(filter.PerPage).Offset((filter.Page - 1) * filter.PerPage)
|
|
}
|
|
if err := db.
|
|
Preload("Client").
|
|
Find(&vendors).Error; err != nil {
|
|
return vendors, total, err
|
|
}
|
|
return vendors, total, nil
|
|
}
|
|
|
|
func (r *vendorRepository) Update(ctx context.Context, tx *gorm.DB, vendor entities.MVendorEntity) (entities.MVendorEntity, error) {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
if err := tx.WithContext(ctx).Save(&vendor).Error; err != nil {
|
|
return vendor, err
|
|
}
|
|
return vendor, nil
|
|
}
|
|
|
|
func (r *vendorRepository) Delete(ctx context.Context, tx *gorm.DB, vendorId string) error {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
if err := tx.WithContext(ctx).Delete(&entities.MVendorEntity{}, "id = ?", vendorId).Error; err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|