knex创建数据库并向其中插入数据

zzwlnbp8  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(490)

我正在使用knex with node.js创建一个表并向其中插入一些数据。首先,我先创建表,然后插入数据,但结果是,有时在插入数据时表还没有创建。最后我使用了如下的回调。现在我把回电和承诺混在一起,我不确定这是否是件好事。我该怎么做才能使下面的工作不需要回调,并且在插入数据之前仍然注意表的创建?

  1. function executeCallback(next, tableName) {
  2. knex.schema.hasTable(tableName)
  3. .then((exists) => {
  4. if (!exists) {
  5. debug('not exists');
  6. // Table creation for mysql
  7. knex.raw(`CREATE TABLE ${tableName} ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, timestamp BIGINT NOT NULL, deviceId VARCHAR(255) NOT NULL, data JSON )`)
  8. .then((rows) => {
  9. debug(rows);
  10. next('Table created (mysql)');
  11. })
  12. .catch((err) => {
  13. debug(`Error: ${err}`);
  14. next(`Error: ${err}`);
  15. });
  16. } else {
  17. debug('Table exists');
  18. next('Table exists');
  19. }
  20. });
  21. }

.

  1. executeCallback((response) => {
  2. debug('back from callback', response);
  3. debug('insert');
  4. knex(req.body.tableName).insert({
  5. timestamp: req.body.timestamp,
  6. deviceId: req.body.deviceId,
  7. data: req.body.data,
  8. })
  9. .catch((err) => {
  10. debug(`Error: ${err}`);
  11. res.status(500).json({ success: false, message: `Error: ${err}` });
  12. })
  13. .then((dataid) => {
  14. debug(`Inserted with id: ${dataid}`);
  15. res.status(201).json({ success: true });
  16. });
  17. }, req.body.tableName);
7tofc5zh

7tofc5zh1#

一般来说,不鼓励将回调和承诺混合在一起。我建议调查一下 async/await 使用承诺的模式,因为在代码中通常更容易阅读。它与knex-js配合也很好。
节点回调的一个技巧是函数参数的约定,其中第一个参数是错误,第二个参数是成功结果。这样地: function (error, results) {...} 这使得结果很容易检查,比如

  1. if(error) {
  2. // do error stuff
  3. return
  4. }
  5. // do success stuff with `results`

我们可以像这样调用这个函数 next(new Error('bad')) 错误,或 next(null, 'success object') 为了成功。
你的回电 next 只接受一个参数,而不检查其值。结果是“table exists”、“table created”还是“error”与下一步的操作有关。
您可以尝试以下操作:

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

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

展开查看全部

相关问题