package service import ( "context" "fmt" "git.nobla.cn/golang/aeus-admin/models" "git.nobla.cn/golang/aeus-admin/pb" "git.nobla.cn/golang/aeus-admin/pkg/dbcache" "gorm.io/gorm" ) type ( departmentOptions struct { db *gorm.DB } DepartmentOption func(o *departmentOptions) DepartmentService struct { opts *departmentOptions } ) func WithDepartmentDB(db *gorm.DB) DepartmentOption { return func(o *departmentOptions) { o.db = db } } func (s *DepartmentService) GetDepartmentLabels(ctx context.Context, req *pb.GetDepartmentLabelRequest) (res *pb.GetDepartmentLabelResponse, err error) { res = &pb.GetDepartmentLabelResponse{} res.Data, err = dbcache.TryCache(ctx, fmt.Sprintf("department:labels"), func(tx *gorm.DB) ([]*pb.DepartmentLabelValue, error) { values := make([]*models.Department, 0) if err = tx.Find(&values).Error; err == nil { items := make([]*pb.DepartmentLabelValue, 0, len(values)) for _, v := range values { items = append(items, &pb.DepartmentLabelValue{ Label: v.Name, Value: v.Id, }) } return items, nil } else { return nil, err } }, dbcache.WithDB(s.opts.db), dbcache.WithDependency(dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM departments")), ) return } func NewDepartmentService(cbs ...DepartmentOption) *DepartmentService { opts := &departmentOptions{} for _, cb := range cbs { cb(opts) } return &DepartmentService{ opts: opts, } }