数据重新格式化的最佳实践/设计模式

时间:2018-10-18 18:38:54

标签: ruby-on-rails design-patterns

我的项目是连接两个主要服务的微服务,我的项目从一台服务器获取数据,格式化数据,然后使用该数据生成XML文件,然后将XML上传到另一服务。我只是想知道这种微服务是否有任何设计模式。

这是从后端服务器收到的JSON:

{
    "employee_id": 100464,
    "organization_id": 93,
    "start_date": "2018-09-05",
    "first_name": "Tom",
    "departments": [
        {
            "id": 2761,
            "name": "Sale",
            "organization_id": 93
        },
        {
            "id": 2762,
            "name": "Product",
            "organization_id": 93
        }
    ],
    "primary_department": {
        "id": 2761,
        "name": "Product",
        "organization_id": 93
    }
}

这是我想要的数据格式,所以我需要做一些数据格式化:

{
    "employee_id": 100464,
    "organization_id": 93,
    "first_name": "Tom",
    "target_department": {
        "department_id": 2761,
        "name": "Product",
        "organization_id": 93,
        "is_primary_department": true
    }
}

确定target_department的逻辑是

departments = hsh.delete :departments
primary_department = hsh.delete :primary_department
hsh[:target_department] = departments.select do |department|
  department[:id] ==another_obj[:group_id]
end.first
hsh[:target_department][:is_home_department] = (hsh[:target_department][:id] == primary_department[:id])
hsh[:target_department][:department_id] = hsh[:target_department].delete :id

如您所见,我需要删除,重命名和重新格式化属性和数据结构。

在此过程中,存在许多潜在问题:属性不存在? 我的问题是从编程设计的角度来看处理此问题的最佳实践是什么?

我正在使用Rails,所以任何出色的宝石或项目都在处理类似的问题?

2 个答案:

答案 0 :(得分:1)

我不了解最佳做法,但这应该可以做您想要的。

{
  "employee_id": 100464,
  "organization_id": 93,
  "start_date": "2018-09-05",
  "first_name": "Tom",
  "departments": [
    {
      "id": 2761,
      "name": "Sale",
      "organization_id": 93
    },
    {
      "id": 2762,
      "name": "Product",
      "organization_id": 93
    }
  ],
  "primary_department": {
    "id": 2761,
    "name": "Product",
    "organization_id": 93
  }
}.with_indifferent_access.except(:start_date, :departments).transform_keys do |k|
  k == 'primary_department' ? 'target_department' : k
end.tap do |hsh|
  if hsh['target_department']
    hsh['target_department']['is_primary_department'] = true
    hsh['target_department']['department_id'] = hsh['target_department']['id']
    hsh['target_department'].delete('id')
  end
  puts hsh
end

在控制台中,它将返回:

{
  "employee_id"=>100464,
  "organization_id"=>93,
  "first_name"=>"Tom",
  "target_department"=>{
    "name"=>"Product", 
    "organization_id"=>93, 
    "is_primary_department"=>true, 
    "department_id"=>2761
  }
}

顺便说一句,在示例输出中,您将target_department名称显示为“ aProduct”。那是错字吗?

答案 1 :(得分:0)

以编程方式直接处理json / xml类型数据通常很乏味。我曾经在一家无处不在的公司工作,这很痛苦。我建议将数据反序列化为对象图表示形式。还具有可以通过查询/处理输入对象图来构造的结果类。然后只需将结果对象序列化到最后的json。

您可能会找到一个内置或开源的解决方案来为您处理序列化和反序列化。