NestJS的新功能,并遇到了一个问题。对于我们的部署,我们需要从AWS Parameter Store(系统管理器)中获取配置,包括数据库连接字符串。我有一个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参数存储的任何内容。在StackOverflow上也存在一个现有问题(未回答)。

谢谢!

最佳答案

你能做这样的事情吗?

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

关于node.js - 使用AWS参数存储的NestJs TypeORM配置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55911569/

10-09 21:30