yintai2/app/common/dao/resource.go

127 lines
3.0 KiB
Go

package dao
import (
"errors"
"fmt"
"yintai-api/app/common/model"
"gorm.io/gorm"
)
type Resource struct {
db *gorm.DB
}
func NewResource(db ...*gorm.DB) *Resource {
return &Resource{db: getDB(db...)}
}
func (r *Resource) TableName() string {
return "yt_resource"
}
func (r *Resource) Create(m *model.Resource) error {
return r.db.Table(r.TableName()).Create(m).Error
}
func (r *Resource) Update(m *model.Resource) error {
return r.db.Table(r.TableName()).Save(m).Error
}
func (r *Resource) Delete(id int64) error {
return r.db.Table(r.TableName()).Where("id = ?", id).Delete(&Resource{}).Error
}
func (r *Resource) Get(id int64) (*model.Resource, error) {
var res model.Resource
if err := r.db.Table(r.TableName()).Where("id = ?", id).First(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &res, nil
}
func (r *Resource) Exists(id int64) (bool, error) {
var count int64
if err := r.db.Table(r.TableName()).Where("id = ?", id).Count(&count).Error; err != nil {
return false, err
}
return count > 0, nil
}
func (r *Resource) List(name, types, code, method, path string, page, size int, sort string) ([]*model.Resource, int64, error) {
var res []*model.Resource
var count int64
tx := r.db.Table(r.TableName())
if name != "" {
tx = tx.Where("name LIKE ?", fmt.Sprintf("%%%s%%", name))
}
if types != "" {
tx = tx.Where("type = ?", types)
}
if path != "" {
tx = tx.Where("path LIKE ?", fmt.Sprintf("%%%s%%", path))
}
if method != "" {
tx = tx.Where("method = ?", method)
}
if err := tx.Count(&count).Error; err != nil {
return nil, 0, err
}
if sort != "" {
tx = tx.Order(sort)
} else {
tx = tx.Order("id desc")
}
if err := tx.Offset((page - 1) * size).Limit(size).Find(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, 0, nil
}
return nil, 0, err
}
return res, count, nil
}
func (r *Resource) GetByIds(ids []int64) ([]*model.Resource, error) {
var res []*model.Resource
if err := r.db.Table(r.TableName()).Where("id in (?)", ids).Find(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return res, nil
}
func (r *Resource) RoleGet(roleId int64) ([]*model.Resource, error) {
var res []*model.Resource
tx := r.db.Table(NewRoleResource().TableName()+" as rr").Where("rr.role_id = ?", roleId)
tx = tx.Joins(fmt.Sprintf(" JOIN %s r ON r.id = rr.resource_id", r.TableName()))
if err := tx.Select("r.*").Order("id desc").Find(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return res, nil
}
func (r *Resource) GetMaps(maps string) ([]*model.Resource, error) {
var res []*model.Resource
if err := r.db.Table(r.TableName()).Where("maps LIKE ?", fmt.Sprintf("%s/%%", maps)).Find(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return res, nil
}