【问题标题】:Knex creating database and inserting data to itKnex 创建数据库并向其插入数据
【发布时间】:2018-11-25 08:10:51
【问题描述】:

我正在使用带有 node.js 的 Knex 创建一个表并向其中插入一些数据。首先,我首先创建表,然后插入数据,但它最终导致有时在插入数据时尚未创建表。然后我最终使用了如下回调。现在我正在混合回调和承诺,我不确定这是否是一件好事。我该怎么做才能在没有回调的情况下进行后续工作,并且仍然注意在插入数据之前创建表?

function executeCallback(next, tableName) {
 knex.schema.hasTable(tableName) 
.then((exists) => {
  if (!exists) {
    debug('not exists');
    // Table creation for mysql
    knex.raw(`CREATE TABLE ${tableName} ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, timestamp BIGINT NOT NULL, deviceId VARCHAR(255) NOT NULL, data JSON )`)
      .then((rows) => {
        debug(rows);
        next('Table created (mysql)');
      })
      .catch((err) => {
        debug(`Error: ${err}`);
        next(`Error: ${err}`);
      });
  } else {
    debug('Table exists');
    next('Table exists');
  }
});
}

.

executeCallback((response) => {
  debug('back from callback', response);
  debug('insert');
  knex(req.body.tableName).insert({
    timestamp: req.body.timestamp,
    deviceId: req.body.deviceId,
    data: req.body.data,
  })
    .catch((err) => {
      debug(`Error: ${err}`);
      res.status(500).json({ success: false, message: `Error: ${err}` });
    })
    .then((dataid) => {
      debug(`Inserted with id: ${dataid}`);
      res.status(201).json({ success: true });
    });
}, req.body.tableName);

【问题讨论】:

标签: mysql node.js callback promise


【解决方案1】:

通常不鼓励将回调和 Promises 混合使用。我建议研究使用 Promises 的 async/await 模式,因为这通常更容易在代码中阅读。它也适用于 knex js。

Node 回调的一个技巧是函数参数的约定,其中第一个参数是错误,第二个是成功结果。像这样:function (error, results) {...} 这使得结果很容易检查,比如

if(error) { 
  // do error stuff 
  return
}
// do success stuff with `results`

人们可以像 next(new Error('bad')) 这样调用该函数来表示错误,或者 next(null, 'success object') 表示成功。

你的回调next 只接受一个参数,你没有检查它的值。结果是“表存在”、“表已创建”还是“错误”对您接下来的操作很重要。

你可以试试这样的:

async function handleInsert(tableName, res) {
  try {
    let hasTable = await knex.schema.hasTable(tableName)
    if(!exists) {
      let createResult = await knex.raw(`CREATE TABLE...`)
      // check create results, throw if something went wrong
    }
    //table guaranteed to exist at this point
    let insertResult = await knex(req.body.tableName).insert({
      timestamp: req.body.timestamp,
      deviceId: req.body.deviceId,
      data: req.body.data,
    })
    debug(`Inserted with id: ${insertResult}`) //might need insertResult[0]
    res.status(201).json({ success: true })
  } catch(err) {
    // any error thrown comes here
    console.log('Server error: ' + err)
    res.error('Bad thing happened, but do not tell client about your DB')
  }
}

还有一件事。通常,您可以假设您需要的表已经存在。或者使用migration 在服务器启动/更新时构建您的数据库。

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2018-09-16
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    相关资源
    最近更新 更多