package model import ( "context" "errors" "fmt" "github.com/zeromicro/go-zero/core/stores/cache" "github.com/zeromicro/go-zero/core/stores/sqlc" "github.com/zeromicro/go-zero/core/stores/sqlx" "youtu_server/game_open_api/internal/types" ) var _ GameScoreModel = (*customGameScoreModel)(nil) const ( cacheEcpmRankListPrefix = "cache:ecpm:game:rankList:appId:" cacheEcpmUserRankPrefix = "cache:ecpm:game:userRank:userId:" ) type ( // GameScoreModel is an interface to be customized, add more methods here, // and implement the added methods in customGameScoreModel. GameScoreModel interface { gameScoreModel GetRankList(ctx context.Context, appId uint64, userId uint64) ([]types.RankingData, error) GetUserRank(ctx context.Context, appId uint64, userId uint64) (*types.RankingData, error) } customGameScoreModel struct { *defaultGameScoreModel } ) // NewGameScoreModel returns a model for the database table. func NewGameScoreModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) GameScoreModel { return &customGameScoreModel{ defaultGameScoreModel: newGameScoreModel(conn, c, opts...), } } func (m *defaultGameScoreModel) GetRankList(ctx context.Context, appId uint64, userId uint64) (resp []types.RankingData, err error) { ecpmGameScoreAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmRankListPrefix, appId) err = m.QueryRowCtx(ctx, &resp, ecpmGameScoreAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error { query := "SELECT game_score.score,app_user.nickname,app_user.avatar,game_score.app_user_id,rank() over(ORDER BY game_score.score desc) t_rank FROM `game_score` JOIN app_user ON app_user.id=game_score.app_user_id WHERE game_score.app_account=? ORDER BY game_score.score DESC LIMIT 20" return conn.QueryRowsPartialCtx(ctx, v, query, appId) }) switch { case err == nil: return resp, nil case errors.Is(err, sqlc.ErrNotFound): return nil, ErrNotFound default: return nil, err } } func (m *defaultGameScoreModel) GetUserRank(ctx context.Context, appId uint64, userId uint64) (resp *types.RankingData, err error) { ecpmGameScoreAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmUserRankPrefix, userId) var res []types.RankingData err = m.QueryRowCtx(ctx, &res, ecpmGameScoreAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error { query := `SELECT app_user.nickname, app_user.avatar, gs.score, gs.app_user_id, gs.t_rank FROM ( SELECT game_score.score, game_score.app_user_id, game_score.app_account, rank() over (ORDER BY game_score.score DESC) t_rank FROM game_score) AS gs LEFT JOIN app_user ON app_user.id = gs.app_user_id AND gs.app_account = ? WHERE gs.app_user_id = ? LIMIT 1 ` return conn.QueryRowsPartialCtx(ctx, v, query, appId, userId) }) switch { case err == nil: if len(res) == 1 { resp = &res[0] } return resp, nil case errors.Is(err, sqlc.ErrNotFound): return nil, ErrNotFound default: return nil, err } }