如何使用异步knexfile

问题描述

尝试将配置导出为异步功能时,knex出现问题。

我的knexfile是:

async function fetchConfiguration() {
  
  return {
    staging:{
      client: 'MysqL',connection: {
      host : 'dbIp',user : 'user',password : 'password',database : 'myDatabase'
      }
    }
  }
  
}

module.exports = async () => {
  const configuration = await fetchConfiguration();
  return {
    ...configuration
  }
};

我的connection.js是:

const knex = require('knex');
const configuration = require('../../knexfile');

var connection = knex(configuration.staging);

module.exports = connection;

但是在运行时,出现此错误

C:\Users\fabio\Documents\Projetos_CVC\uptime\uptime\API\node_modules\knex\lib\knex.js:22
  if (arguments.length === 0 || (!config.client && !config.dialect)) {
                                         ^

TypeError: Cannot read property 'client' of undefined
    at Knex (C:\Users\fabio\Documents\Projetos_CVC\uptime\uptime\API\node_modules\knex\lib\knex.js:22:42)
    at Object.<anonymous> (C:\Users\fabio\Documents\Projetos_CVC\uptime\uptime\API\src\database\connection.js:4:18)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (C:\Users\fabio\Documents\Projetos_CVC\uptime\uptime\API\src\controllers\CheckController.js:1:20)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)

很快我将需要在该项目中使用保管库和领事,因此不使用异步创建会很复杂。 感谢您的帮助。

解决方法

由于您的配置是异步的,因此您需要等待它。

这意味着,为了配置连接,您的代码应该一直都是异步的。

它看起来应该像这样:

// dbConfig.js
async function fetchConfiguration() {
  
  return {
    staging:{
      client: 'mysql',connection: {
      host : 'dbIp',user : 'user',password : 'password',database : 'myDatabase'
      }
    }
  }
  
}

module.exports = async () => {
  const configuration = await fetchConfiguration();
  return {
    ...configuration
  }
};
// db.js
const knex = require('knex');
const configuration = require('../../dbConfig');

const config = await configuration();
// --------------^ you are exporting an async function,it must be awaited

const connection = knex(config.staging);
module.exports = connection;

ps,top level await不受所有节点版本的支持,请检查您的节点是否支持它。如果没有,则可以使用链接中描述的iffe包装代码。