【问题标题】:Knex: Cannot read property 'client' of undefined with async connectionKnex:无法使用异步连接读取未定义的属性“客户端”
【发布时间】:2023-04-10 00:46:02
【问题描述】:

由于某种原因,当使用const knex = require('./knex'); 访问数据库时,我得到了TypeError: Cannot read property 'client' of undefined,它指的是knex.js 中的第二行代码(参见下面的代码)。当我没有围绕导出的异步但我无法获取生产和登台的凭据时,它可以工作。

我有一个具有以下设置的knexfile.js 文件:

const { getAwsDbCredentials } = require('./config/aws');
    
const defaultConfig = {
  client: 'mysql',
  pool: {
    afterCreate(connection, callback) {
      connection.query("SET time_zone='+00:00';", (err) => {
        callback(err, connection);
      });
    },
  },
  migrations: {
    directory: './migrations',
  },
};

const defaultConnectionConfig = {
  charset: 'utf8mb4',
  dateStrings: true,
  timezone: 'UTC',
  typeCast(field, next) {
    if (field.type === 'TINY' && field.length === 1) {
      const value = field.string();
      return value ? value === '1' : null;
    }
    return next();
  },
};

const rdsConnectionConfig = async () => {
  const { SecretString } = await getAwsDbCredentials();

  const { dbname, host, password, port, username } = JSON.parse(SecretString);

  return {
    ...defaultConnectionConfig,
    database: dbname,
    host,
    password,
    port,
    user: username,
  };
};

module.exports = async () => {
  return {
    test: {
      ...defaultConfig,
      connection: {
        ...defaultConnectionConfig,
        user: 'xxx',
        password: 'xxx',
        database: 'xxx',
      },
      seeds: {
        directory: './seeds/test',
      },
    },
    development: {
      ...defaultConfig,
      connection: {
        ...defaultConnectionConfig,
        user: 'xxx',
        password: 'xxx',
        database: 'xxx',
      },
      seeds: {
        directory: './seeds/development',
      },
    },
    production: {
      ...defaultConfig,
      connection: await rdsConnectionConfig(),
      seeds: {
        directory: './seeds/production',
      },
    },
    staging: {
      ...defaultConfig,
      connection: await rdsConnectionConfig(),
      seeds: {
        directory: './seeds/staging',
      },
    },
  };
};

还有一个具有以下设置的knex.js 文件:

const config = require('../../../knexfile.js')[process.env.NODE_ENV];

module.exports = require('knex')(config);

【问题讨论】:

    标签: javascript node.js amazon-web-services knex.js


    【解决方案1】:

    您正在导出一个函数,该函数返回一个对象,因此,您需要调用它。

    const getConfig= require('../../../knexfile.js')
    
    module.exports = require('knex')(getConfig()[process.env.NODE_ENV]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 2022-01-09
      • 2021-11-21
      相关资源
      最近更新 更多