使用AWS参数存储的NestJs TypeORM配置 [英] NestJs TypeORM configuration using AWS Parameter Store
问题描述
NestJS的新功能,遇到了一个问题.对于我们的部署,我们需要从AWS Parameter Store(系统管理器)获取我们的配置,包括数据库连接字符串.我有一个ConfigModule和ConfigService,它根据参数存储路径为我的环境检索所有参数存储条目:
new to NestJS and have come across an issue. For our deployments we need to get our configuration from AWS Parameter Store (Systems Manager), including the database connection string. I have a ConfigModule and ConfigService which retrieves all the parameter store entries for my environment based on the param store path:
这是我的配置服务:
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'];
}
}
这是主要的应用模块声明块:
Here is the main app module declaration block:
@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秒,因此发生未定义"错误,因为在TypeORM尝试加载连接字符串时,"this.awsParamStoreEntries"仍未定义.
As you can see I am telling TypeORM to call the getDatabase() method in the ConfigService but the problem is that it takes about 3-4 seconds for the parameter store entries to load so an "undefined" error occurs because "this.awsParamStoreEntries" is still undefined when TypeORM tries to load the connection string.
已经在网络上进行搜索以查看是否已完成,但是找不到以这种方式使用NestJS/TypeORM/AWS参数存储的任何内容.在StackOverflow上也存在一个现有的(未回答的)问题.
Have scoured the web to see if this has been done but could not find anything that uses NestJS / TypeORM / AWS Parameter Store in this way. There is an existing (unanswered) question here on StackOverflow as well.
谢谢!
推荐答案
你能做这样的事情吗?
import { TypeOrmOptionsFactory, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigService } from './config.service';
import { Injectable } from '@nestjs/common';
@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
constructor(private readonly configService: ConfigService) {
}
async createTypeOrmOptions(): Promise<TypeOrmModuleOptions> {
this.configService.awsParamStoreEntries = await this.configService.loadAwsParameterStoreEntries(this.configService.awsParamStorePath);
return {
url: this.configService.getDatabase(),
};
}
}
@Module({
imports: [
ConfigModule,
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useClass: TypeOrmConfigService,
}),
CoreModule,
AuthModule
],
controllers: [AppController],
providers: [AppService],
})
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as AWS from 'aws-sdk';
import { Injectable } from '@nestjs/common';
@Injectable()
export class ConfigService {
private readonly envConfig: { [key: string]: string };
awsParamStoreEntries: { [key: string]: string }[];
private readonly awsParamStorePath: string;
constructor(awsParamStorePath: string, filePath: string) {
this.envConfig = dotenv.parse(fs.readFileSync(filePath));
this.awsParamStorePath = awsParamStorePath;
}
loadAwsParameterStoreEntries(pathPrefix: string) {...
https://docs.nestjs.com/techniques/database
这篇关于使用AWS参数存储的NestJs TypeORM配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!