nodejs mysql 函数的设计模式 - 带迭代的条件语句,更改值

nodejs mysql design pattern for function - conditional statement with iteration, change the values

我有两个节点 mysql 语句来检索数据。

//one query
pool.getConnection(function(err, connection) {
connection.query('select * from tablejohn' , function(err, rows, fields) {  
infoCleanup(rows,"rows[i]");
} });


//2 queries (multiqueries in one statement)
pool.getConnection(function(err, connection) {
connection.query('select count(*)  as Companycount from tablejohn WHERE elif in (3,4);select * FROM tablejohn WHERE  elif in (3,4)', function(err, rows, fields) {
infoCleanup(rows,"rows[1][i]");
} });

迭代和更改值我为此创建了一个函数

var infoCleanup = function(rows,type){

if (type=="rows[i]"){
//iterate and change the value
for(var i=0;i<rows.length; i++)
rows[i].a = toTittleCase(rows[i].a);
rows[i].b = toTittleCase(rows[i].b);
rows[i].c = toTittleCase(rows[i].c);
}

else if(type=="rows[1][i]"){
//iterate and change the value
for(var i=0;i<rows[1].length; i++)
rows[1][i].a = toTittleCase(rows[1][i].a);
rows[1][i].b = toTittleCase(rows[1][i].b);
rows[1][i].c = toTittleCase(rows[1][i].c);
}

}

现在我一直在使用上面的 infoCleanup(rows,type) 函数并从那里设置条件语句。

问题是如何改进我的 infoCleanUp 函数以获得更好的可维护代码(即设计模式、oop 等)?

如你所见,两个条件语句的执行语句("iterate and change the value")做同样的事情,唯一不同的是 变量 rows[i] 或变量 rows[1][i] 。所以我想我们在这种情况下没有条件语句并减少代码行。

实际上,这是一段过于局部的代码,无法对其应用一些 OOP 模式。 我会把它分解成函数:

// Test data
data_rows = [
  {a: 'test', 'b': 'b', 'c': 'c'},
  {a: 'test_two', 'b': 'b_two', 'c': 'c_two'}
];

data_rows1 = [
  [],
  [
    {a: 'test', 'b': 'b', 'c': 'c'},
    {a: 'test_two', 'b': 'b_two', 'c': 'c_two'}
  ]
];

// Convert function
var convertTitle = function(row) {
  row.a = row.a.toUpperCase();
  row.b = row.b.toUpperCase();
  row.c = row.c.toUpperCase();
}

// Cleanup loop
var infoCleanup = function(rows, getter) {
  for(var i=0;i<rows.length; i++) {
      convertTitle(getter(rows, i));
  }
}

// The anonymous function captures the difference (rows[i] vs rows[1][i])
infoCleanup(data_rows, function(rows, i) { return rows[i]; } );
alert(JSON.stringify(data_rows));


infoCleanup(data_rows1, function(rows, i) { return rows[1][i]; } );
alert(JSON.stringify(data_rows1));