xmysql改造的原因

老版本的常规操作:4层深度,找sql不易

  • handler/upload.go
func (h *FileHandler) GetFileSummary(ctx context.Context, req *pb.GetFileSummaryReq, rsp *pb.GetFileSummaryResp) error {
    file, err := h.repo.GetFileInfo(ctx, req.FileID)
    if err != nil {
        return err
    }

    ....
    return nil
}
  • dao/repo.go
type Repo interface {
    ...
    // 获取文件信息
    GetFileInfo(ctx context.Context, id int64) (*entity.FileInfo, error)
    // 删除文件信息
    DeleteFileInfo(ctx context.Context, id int64) error

    Close() error
}
  • dao/file.go
// 持久化文件信息
func (r *repo) CreateFileInfo(ctx context.Context, file *entity.FileInfo) error {
    ret, err := r.stmts.GetNamedStmt("CreateFileInfo").Exec(ctx, file)
    if err != nil {
        return errors.InternalServerError("file.dao.CreateFileInfo", err.Error())
    }
    file.ID, err = ret.LastInsertId()
    return err
}
  • dao/init.go
func Init(mysqlDSN string) xmysql.StmtsDB {
    stmtsDB := xmysql.NewDB(mysqlDSN, 2, 10)

    fileInfo := new(entity.FileInfo)
    stmtsDB.MustPrepareNamedStmts(map[string]string{
    ...
        "CreateFileInfo": xmysql.GetInsertSQLFromObj(FileInfoTableName, fileInfo),
    })

    stmtsDB.MustPrepareStmts(map[string]string{
    ...
        "GetFileInfo":    "SELECT * FROM `" + FileInfoTableName + "` WHERE id = ?",
        "DeleteFileInfo": "DELETE FROM `" + FileInfoTableName + "` WHERE id = ?",
    })

    return stmtsDB
}

改良措施一:引入TableHelper、TableHelperX

  • handler/channel.go
func (h *ChannelHandler) GetChannelIDsUserJoined(
    ctx context.Context,
    req *pb.GetChannelIDsUserJoinedReq,
    rsp *pb.GetChannelIDsUserJoinedRsp,
) error {
    uid := req.UserID
    cids := h.repo.UserChannelGetAllChannelIDsByUserID(ctx, uid)
    rsp.ChannelIDs = cids
    return nil
}
  • dao/user_channel.go
func (r *Repo) UserChannelGetAllChannelIDsByUserID(ctx context.Context, userID int64) []int64 {
    table := TableX(TableNameUserChannel)
    var l []int64
    c := xmysql.Map{
        "user_id": userID,
    }
    kw := xmysql.NewKeyWord()
    kw.Field = "`channel_id`"
    table.GetAll(ctx, c, &l, kw)
    return l
}

改良措施二:引入Model层

  • handler/handler.go
func (h *AgoraHandler) LeaveVoiceSubchannel(ctx context.Context, req *pb.VoiceSubchannelReq, rsp *empty.Empty) error {
    o := model.NewUserVoiceSubchannelModel()
    newData := xmysql.Map{
        o.Fields.State: 0,
        o.Fields.UpdateAt: xtime.Now(),
    }
    o.Update(ctx, newData, req.UserID)
    pushLeaveVoiceSubchannel(ctx, req)
    return nil
}

新框架说明

handler 暂不变

entity层 升级

  • 自动生成的代码:autogenXXX.go
  • 可修改的代码:XXX.go (写一般写 转化Proto的对象)

dao层 =》 model层

Copyright © xinyan all right reserved,powered by Gitbook该文件修订时间: 2020-07-29 10:10:43

results matching ""

    No results matching ""