doufuxing8691 2018-06-17 11:42
浏览 32
已采纳

域和数据库之间的映射

I am creating application which get the data from the database and pass them to frontend as JSON.

I think it can be a good idea to create separate structs for the data which I get from the database and the data which I pass to REST services. I am right or it is my mistake ?

In this case I need to map the structs from one layer to another. I do it in the database layer now:

func (ds *DataStore) AddUnit(_unit models.Unit) {

    unit := Unit{}
    unit.Name = _unit.Name
    unit.Description = _unit.Description
    db.Create(&unit)
}

func (ds *DataStore) UpdateUnit(id int, _unit models.Unit) models.Unit {

    unit := Unit{}
    db.First(&unit, id)
    unit.Name = _unit.Name
    unit.Description = _unit.Description
    db.Save(&unit)

    return _unit
}

Now I have this code in each method for each entity in my code. May be there is some way or library to extract this mapping functionality and describe it using declarative way in the separate file ?

  • 写回答

1条回答 默认 最新

  • dongxinxin7809 2018-06-17 13:16
    关注

    You could look for, and use a library; the problem with libs is that they are trying to cater to unknown problems. The author of the library doesn't know how it will be used. This can, in some situations, make them much slower, less flexible, and more complicated that just writing the code yourself.

    To start you should extract the duplicate logic from the DataStore:

    // extract the logic of copying across the fields to a function
    func setFields(u Unit, unit models.Unit) Unit {
        u.Name = unit.Name
        u.Description = unit.Description
        return u
    }
    
    func (ds *DataStore) AddUnit(_unit models.Unit) {
        // trimmed ...
        unit := setFields(Unit{}, _unit)
        // trimmed ...
    }
    
    func (ds *DataStore) UpdateUnit(id int, _unit models.Unit) models.Unit {
        unit := Unit{}
        db.First(&unit, id)
    
        unit = setFields(unit, _unit)
    
        // trimmed ...
    }
    

    You may then also consider extracting the function call of setFields to a new interface:

    type unitSetter interface {
       setFields(u Unit, unit models.Unit) Unit
    }
    

    And add this to the DataStore to make the code more extensible, reusable, and testable.

    type DataStore struct {
        // trimmed ...
        units unitSetter
    }
    
    func (ds *DataStore) AddUnit(_unit models.Unit) {
        // trimmed ...
        unit := ds.units.setFields(Unit{}, _unit)
        // trimmed ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错