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 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动