【发布时间】:2020-10-10 11:21:21
【问题描述】:
我正在使用 GraphQL 和 go-pg。
我有很多这样的实体:
type Player struct {
ID int
CreatedAt time.Time `pg:"default:now(),notnull"`
TeamID int `pg:",notnull"`
Team *Team
Type int
Score int64 `pg:",notnull"`
Note *string
// and others...
}
type PlayerInput struct {
TeamID int
Type int
Score int64
Note *string
// and others...
}
我有很多次这样的功能:
func (db *postgres) Update(context context.Context, id int, input types.PlayerInput) (*types.Player, error) {
var actualPlayer types.Player
newPlayer := graphqlToDB(&input)
tx, err := db.Begin()
//handle err
err = tx.Model(&actualPlayer).Where("id = ?", id).For("UPDATE").Select()
// handle err and rollback
actualPlayer.TeamID = newPlayer.TeamID
actualPlayer.Type = newPlayer.Type
actualPlayer.Score = newPlayer.Score
actualPlayer.Note = newPlayer.Note
// and others...
_, err = tx.Model(&actualPlayer).WherePK().Update()
// handle err and rollback
err = tx.Commit()
//handle err
return &actualPlayer, nil
}
func graphqlToDB(input *types.PlayerInput) *types.Player {
var output = &types.Player{
TeamID: input.TeamID,
Type: input.Type,
Score: input.Score,
Note: input.Note,
// and others...
}
if input.Type == "example" {
output.Score = 10000000
}
return output
}
我的项目中的每个实体都有此代码,我想限制/避免冗余代码,特别是:
-
每次从 Graphql 输入类型转换
newPlayer := graphqlToDB(&input) -
每次手动更新这些(和其他)字段
actualPlayer.TeamID = newPlayer.TeamID actualPlayer.Type = newPlayer.Type actualPlayer.Score = newPlayer.Score actualPlayer.Note = newPlayer.Note -
每次打开和关闭数据库事务
tx, err := db.Begin()
我是在求月亮吗?
【问题讨论】:
标签: go design-patterns architecture refactoring