This commit is contained in:
xiabin 2025-01-20 14:37:14 +08:00
parent a9403daab5
commit e2bff25b45
11 changed files with 181 additions and 36 deletions

6
game_open_api/auth.api Normal file
View File

@ -0,0 +1,6 @@
syntax = "v1"
type Auth {
Token string `json:"token"`
}

View File

@ -1,5 +1,6 @@
syntax = "v1"
import "auth.api"
type DouyinCode2UserIdRequest {
AppId string `form:"appId"`
@ -17,7 +18,7 @@ type DouyinCode2UserIdRequest {
service game_open_api-api {
@handler douyinCode2UserId
get /code2userId (DouyinCode2UserIdRequest) returns (string)
get /code2userId (DouyinCode2UserIdRequest) returns (Auth)
}

View File

@ -1,12 +1,19 @@
syntax = "v1"
type SetUserGameScoreRequest {
Score uint64 `json:"score"`
}
type RankingData {
Nickname string `json:"nickname" db:"nickname"` // 昵称
Avatar string `json:"avatar" db:"avatar"` // 头像
Score uint32 `json:"score" db:"score"` // 得分
UserId uint64 `json:"-" db:"app_user_id"` // 用户 ID
Rank uint32 `json:"rank" db:"t_rank"` // 排名
Self bool `json:"self" db:"-"` // 是否是自己
}
@server(
group: game
prefix: /v1/game // 对当前 Foo 语法块下的所有路由,新增 /v1 路由前缀,不需要则请删除此行
@ -14,10 +21,10 @@ type SetUserGameScoreRequest {
timeout: 3s // 对当前 Foo 语法块下的所有路由进行超时配置,不需要则请删除此行
maxBytes: 1048576 // 对当前 Foo 语法块下的所有路由添加请求体大小控制,单位为 byte,goctl 版本 >= 1.5.0 才支持
)
service game_open_api-api {
service game_open_api-api {
@handler rankingList
get /ranking/list
get /ranking/list returns ([]RankingData)
@handler rankingSetScore
post /ranking/set_score (SetUserGameScoreRequest)

View File

@ -11,11 +11,11 @@ import (
func RankingListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := game.NewRankingListLogic(r.Context(), svcCtx)
err := l.RankingList()
resp, err := l.RankingList()
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.Ok(w)
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@ -29,7 +29,9 @@ func NewDouyinCode2UserIdLogic(ctx context.Context, svcCtx *svc.ServiceContext)
}
}
func (l *DouyinCode2UserIdLogic) DouyinCode2UserId(req *types.DouyinCode2UserIdRequest) (resp string, err error) {
func (l *DouyinCode2UserIdLogic) DouyinCode2UserId(req *types.DouyinCode2UserIdRequest) (resp *types.Auth, err error) {
resp = new(types.Auth)
douyinCli, err := app_api_helper.DouyinCli.GetDouYinOpenApi(req.AppId)
if err != nil {
return
@ -56,17 +58,11 @@ func (l *DouyinCode2UserIdLogic) DouyinCode2UserId(req *types.DouyinCode2UserIdR
Unionid: res.Unionid,
AnonymousOpenid: res.AnonymousOpenid,
}
result, err := l.svcCtx.AppUser.Insert(l.ctx, aui)
err = l.svcCtx.AppUser.FindOrCreate(l.ctx, aui)
if err != nil {
return
}
id, err := result.LastInsertId()
if err != nil {
return
}
aui.Id = uint64(id)
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Unix() + l.svcCtx.Config.Auth.AccessExpire
claims["iat"] = l.svcCtx.Config.Auth.AccessExpire
@ -79,6 +75,6 @@ func (l *DouyinCode2UserIdLogic) DouyinCode2UserId(req *types.DouyinCode2UserIdR
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
resp, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
resp.Token, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
return
}

View File

@ -2,9 +2,10 @@ package game
import (
"context"
"youtu_server/game_open_api/internal/svc"
"youtu_server/game_open_api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
"youtu_server/game_open_api/internal/svc"
)
type RankingListLogic struct {
@ -21,8 +22,35 @@ func NewRankingListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Ranki
}
}
func (l *RankingListLogic) RankingList() error {
// todo: add your logic here and delete this line
return nil
func (l *RankingListLogic) RankingList() (resp []types.RankingData, err error) {
at, err := svc.GetCtxToken(l.ctx)
if err != nil {
return nil, err
}
resp, err = l.svcCtx.GameScore.GetRankList(l.ctx, at.AppId, at.UserId)
if err != nil {
return nil, err
}
var flag bool
for i := range resp {
if resp[i].UserId == at.UserId {
resp[i].Self = true
flag = true
break
}
}
if !flag {
userRank, err := l.svcCtx.GameScore.GetUserRank(l.ctx, at.AppId, at.UserId)
//_, _ = userRank, err
if err != nil {
return nil, err
}
userRank.Self = true
resp = append(resp, *userRank)
}
return
}

View File

@ -29,7 +29,8 @@ func NewWechatCode2UserIdLogic(ctx context.Context, svcCtx *svc.ServiceContext)
}
}
func (l *WechatCode2UserIdLogic) WechatCode2UserId(req *types.WechatCode2UserIdRequest) (resp string, err error) {
func (l *WechatCode2UserIdLogic) WechatCode2UserId(req *types.WechatCode2UserIdRequest) (resp *types.Auth, err error) {
resp = new(types.Auth)
wechatCli, err := app_api_helper.WechatCli.GetWechatOpenApi(req.AppId)
if err != nil {
return
@ -56,19 +57,11 @@ func (l *WechatCode2UserIdLogic) WechatCode2UserId(req *types.WechatCode2UserIdR
Unionid: res.UnionID,
}
//todo 校验唯一
result, err := l.svcCtx.AppUser.Insert(l.ctx, aui)
err = l.svcCtx.AppUser.FindOrCreate(l.ctx, aui)
if err != nil {
return
}
id, err := result.LastInsertId()
if err != nil {
return
}
aui.Id = uint64(id)
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Unix() + l.svcCtx.Config.Auth.AccessExpire
claims["iat"] = l.svcCtx.Config.Auth.AccessExpire
@ -81,7 +74,7 @@ func (l *WechatCode2UserIdLogic) WechatCode2UserId(req *types.WechatCode2UserIdR
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
resp, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
resp.Token, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
return
}

View File

@ -3,12 +3,25 @@
package types
type Auth struct {
Token string `json:"token"`
}
type DouyinCode2UserIdRequest struct {
AppId string `form:"appId"`
Code string `form:"code,optional"`
AnonymousCode string `form:"anonymousCode,optional"`
}
type RankingData struct {
Nickname string `json:"nickname" db:"nickname"` // 昵称
Avatar string `json:"avatar" db:"avatar"` // 头像
Score uint32 `json:"score" db:"score"` // 得分
UserId uint64 `json:"-" db:"app_user_id"` // 用户 ID
Rank uint32 `json:"rank" db:"t_rank"` // 排名
Self bool `json:"self" db:"-"` // 是否是自己
}
type SetAppUserRequest struct {
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`

View File

@ -1,7 +1,10 @@
package model
import (
"context"
"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"
)
@ -12,6 +15,7 @@ type (
// and implement the added methods in customAppUserModel.
AppUserModel interface {
appUserModel
FindOrCreate(ctx context.Context, data *AppUser) (err error)
}
customAppUserModel struct {
@ -25,3 +29,30 @@ func NewAppUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option)
defaultAppUserModel: newAppUserModel(conn, c, opts...),
}
}
func (m *customAppUserModel) FindOrCreate(ctx context.Context, data *AppUser) (err error) {
ecpmAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, data.Id)
var resp AppUser
err = m.QueryRowCtx(ctx, &resp, ecpmAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `openid` = ? limit 1", appUserRows, m.table)
return conn.QueryRowCtx(ctx, v, query, data.Openid)
})
switch err {
case nil:
*data = resp
return nil
case sqlc.ErrNotFound:
res, err := m.Insert(ctx, data)
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
data.Id = uint64(id)
return nil
default:
return err
}
}

View File

@ -1,17 +1,29 @@
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 {
@ -25,3 +37,58 @@ func NewGameScoreModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Optio
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
}
}

View File

@ -1,5 +1,8 @@
syntax = "v1"
import "auth.api"
type WechatCode2UserIdRequest {
AppId string `form:"appId"`
Code string `form:"code"`
@ -15,6 +18,6 @@ type WechatCode2UserIdRequest {
service game_open_api-api {
@handler wechatCode2UserId
get /code2userId (WechatCode2UserIdRequest) returns (string )
get /code2userId (WechatCode2UserIdRequest) returns (Auth )
}