const db = require('../utilities/db.js')
const utils = require('../utilities/utils.js')

/**
 * Query and response helper
 */

const queryAndResponse = (params) => {
  const {
    sql,
    parse,
    req,
    res
  } = params

  if (!sql) throw new Error('sql is not defined')
  if (typeof sql !== 'string') {
    throw new Error('Type of sql is not string')
  }
  if (!res) throw new Error('res object is not defined')
  if (!req) throw new Error('req object is not defined')
  if (parse && typeof parse !== 'function') {
    throw new Error('Type of parse is not defined')
  }

  const connection = db.getConnection()
  new Promise(
    (resolve, reject) => {
      connection.query(
        sql,
        (err, results) => {
          if (err) {
            utils.log(err)
            return reject(err)
          } else {
            resolve(results)
          }
        }
      )
    }
  ).then(
    (result) => res.status(200).json({
      success: true,
      data: parse ? parse(result) : result
    }),
    (err) => res.status(500).json({
      success: false,
      err: err ? 'No error specify' : err.toString()
    })
  )
}

/**
 * Transform to SQL
 */

const transformToSQL = {
  insert: (tableName, dataSet) => {
    let columnsList = []
    let valuesList = []
    for (let key in dataSet) {
      columnsList.push(key)
      valuesList.push(dataSet[key])
    }
    return `INSERT INTO ${tableName} (${columnsList.join(', ')}) ` +
      `VALUES (${valuesList.map((val) => `"${val}"`).join(', ')})`
  },
  update: (tableName, dataSet, where) => {
    let setCondition = []
    for (let key in dataSet) {
      setCondition.push(`${key} = "${dataSet[key]}"`)
    }
    return `UPDATE ${tableName} SET ${setCondition.join(', ')} WHERE ${where}`
  }
}

module.exports = {
  queryAndResponse,
  transformToSQL
}

@@ -1749,16 +1749,474 @@
 where%7D%60%0A
+  %7D,%0A  /**%0A   * receive tableName and filterList which consists of the key and value which%0A   * is needed to be queried%0A   */%0A  filter: (tableName, filterList) =%3E %7B%0A    const keys = Object.keys(filterList)%0A    let queryString = %60SELECT * FROM $%7BtableName%7D WHERE %60%0A    for (let i = 0; i %3C keys.length; i++) %7B%0A      const key = keys%5Bi%5D%0A      queryString += %60$%7Bkey%7D = $%7BfilterList%5Bkey%5D%7D%60 + %60$%7B(i %3C keys.length - 1) ? ' AND ' : ''%7D%60%0A    %7D%0A    return queryString%0A
   %7D%0A%7D%0A%0Am
@@ -2271,9 +2271,8 @@
 mToSQL%0A%7D
-%0A

Add transformtoSQL filter