NestJS 的新手,遇到了一个问题。对于我们的部署,我们需要从 AWS Parameter Store (Systems Manager) 获取我们的配置,包括数据库连接字符串。我有一个 ConfigModule 和 ConfigService,它根据参数存储路径检索我的环境的所有参数存储条目:
这是我的配置服务:
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as AWS from 'aws-sdk';
export class ConfigService {
private readonly envConfig: { [key: string]: string };
private awsParamStoreEntries: { [key: string]: string }[];
constructor(awsParamStorePath: string, filePath: string) {
this.envConfig = dotenv.parse(fs.readFileSync(filePath));
this.loadAwsParameterStoreEntries(awsParamStorePath).then((data) => {
this.awsParamStoreEntries = data;
});
}
loadAwsParameterStoreEntries(pathPrefix: string) {
const credentials = new AWS.SharedIniFileCredentials({ profile: 'grasshopper-parameter' });
AWS.config.credentials = credentials;
const ssm = new AWS.SSM({ region: 'us-west-2' });
var params: { [key: string]: string }[] = [];
return getParams({
Path: '/app/v3/development/',
Recursive: true,
WithDecryption: true,
MaxResults: 10,
}).then(() => {
return params;
});
function getParams(options) {
return new Promise((resolve, reject) => {
ssm.getParametersByPath(options, processParams(options, (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
}));
});
}
function processParams(options, cb) {
return function (err, data) {
if (err) {
return cb(err)
};
data.Parameters.forEach(element => {
let key = element.Name.split('/').join(':')
params.push({ key: key, value: element.Value });
});
if (data.NextToken) {
const nextOptions = Object.assign({}, options);
nextOptions.NextToken = data.NextToken;
return ssm.getParametersByPath(nextOptions, processParams(options, cb));
}
return cb(null);
};
}
}
get(key: string): string {
return this.envConfig[key];
}
getParamStoreValue(key: string): string {
return this.awsParamStoreEntries.find(element => element.key === key)['value'];
}
getDatabase(): string {
return this.awsParamStoreEntries.find(element => element.key === 'ConnectionStrings:CoreDb')['value'];
}
}
这是主要的应用程序模块声明块:
@Module({
imports: [ConfigModule, TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
url: configService.getDatabase()
}),
inject: [ConfigService]
}),
CoreModule, AuthModule],
controllers: [AppController],
providers: [AppService],
})
如您所见,我告诉 TypeORM 在 ConfigService 中调用 getDatabase() 方法,但问题是加载参数存储条目大约需要 3-4 秒,因此会出现“未定义”错误,因为“this.awsParamStoreEntries”当 TypeORM 尝试加载连接字符串时仍然未定义。
已在网上搜索以查看是否已完成,但找不到以这种方式使用 NestJS / TypeORM / AWS Parameter Store 的任何东西。StackOverflow 上也有一个现有的(未回答的)问题。
谢谢!