【发布时间】: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