repository.go 2.3 KB
package domain

import (
	"context"
	"reflect"

	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/db/transaction"
)

func OffsetLimit(page, size int) (offset int, limit int) {
	if page == 0 {
		page = 1
	}
	if size == 0 {
		size = 20
	}
	offset = (page - 1) * size
	limit = size
	return
}

type QueryOptions map[string]interface{}

func NewQueryOptions() QueryOptions {
	options := make(map[string]interface{})
	return options
}
func (options QueryOptions) WithOffsetLimit(page, size int) QueryOptions {
	offset, limit := OffsetLimit(page, size)
	options["offset"] = offset
	options["limit"] = limit
	return options
}

func (options QueryOptions) WithKV(key string, value interface{}) QueryOptions {
	if reflect.ValueOf(value).IsZero() {
		return options
	}
	options[key] = value
	return options
}

func (options QueryOptions) MustWithKV(key string, value interface{}) QueryOptions {
	options[key] = value
	return options
}

func (options QueryOptions) Copy() QueryOptions {
	newOptions := NewQueryOptions()
	for k, v := range options {
		newOptions[k] = v
	}
	return newOptions
}

type IndexQueryOptionFunc func() QueryOptions

// 自定义的一些查询条件

func (options QueryOptions) WithCountOnly() QueryOptions {
	options["countOnly"] = true
	return options
}
func (options QueryOptions) WithFindOnly() QueryOptions {
	options["findOnly"] = true
	return options
}
func (options QueryOptions) WithOrder(order string) QueryOptions {
	options["orderBy"] = order
	return options
}

func LazyLoad[K comparable, T any](source map[K]T, ctx context.Context, conn transaction.Conn, k K, load func(context.Context, transaction.Conn, K) (T, error)) (T, error) {
	if v, ok := source[k]; ok {
		return v, nil
	}
	if v, err := load(ctx, conn, k); err != nil {
		return v, err
	} else {
		source[k] = v
		return v, nil
	}
}

func Values[T any, V any](list []T, each func(item T) V) []V {
	var result []V
	for _, item := range list {
		value := each(item)
		result = append(result, value)
	}
	return result
}

/*************** 索引函数 ****************/
func IndexCompanyId(companyId int64) IndexQueryOptionFunc {
	return func() QueryOptions {
		return NewQueryOptions().WithKV("companyId", companyId)
	}
}
func IndexUserId(userId int64) IndexQueryOptionFunc {
	return func() QueryOptions {
		return NewQueryOptions().WithKV("userId", userId)
	}
}