让我们简化 TypeORM 实体User
:
@Entity()
export class User extends BaseDatabaseEntity {
@Column({
length: 255,
})
public firstName!: string;
@Column({ length: 60 })
@Exclude()
public password: string;
@BeforeUpdate()
@BeforeInsert()
private hashPassword(): void {
const tmpPassword = hashSync(
this.password + 'config.auth.password.secret',
genSaltSync(),
);
this.password = tmpPassword;
}
}
}
我需要将 config.auth.password.secret
替换为 NestJS 的配置(来自 ConfigService 的命名空间):
export default registerAs('app', () => {
return {
password: {
secret: process.env.AUTH_PASSWORD_SECRET,
}
};
});
,但实体不是 NestJS 结构的一部分,所以我不能像往常一样注入(inject)它。
如何在 TypeORM 实体中实现 NestJS 配置?
最佳答案
我也需要这个并想出了解决方法。正如已经说过的,您无法将配置注入(inject)到实体中。
我想出了使用实体中需要的配置值导出对象的解决方案:
初始化应用模块中的配置:
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [defaultConfig]
}),
// .....other imports
]
defaultConfig
是一个收集和检查配置值的函数。最重要的是,它将值设置为 STATIC_CONFIG
对象。
export const STATIC_CONFIG = {
WEB_APP_URL: '',
BASE_URL: '',
};
export const defaultConfig = () => {
const port = +(process.env[ENV_SERVER.PORT] || 3000);
const production = process.env.NODE_ENV === 'production';
const retVal = {
PRODUCTION: production,
PORT: port,
BASE_URL: process.env.BASE_URL || 'http://localhost:3000',
URL_PREFIX: process.env.URL_PREFIX || 'http://localhost:3000',
// ..... plenty of other values
}
if (retVal[ENV_S3.HOST] && !(retVal[ENV_S3.ACCESS] && retVal[ENV_S3.SECRET])) {
// tslint:disable-next-line:no-console
console.error('S3 configuration error: no access or secret set; exiting');
process.exit(1);
}
STATIC_CONFIG.WEB_APP_URL = retVal.WEB_APP_URL;
STATIC_CONFIG.BASE_URL = retVal.BASE_URL;
return retVal;
};
最后,在我的实体中,我使用 STATIC_CONFIG
对象,例如:
@Expose({ name: 'image', toPlainOnly: true, groups: [TG_MOBILE] })
get mobileAppImage() {
return this.id ? `${STATIC_CONFIG.BASE_URL}/static/image/${this.id}` : undefined;
}
关于typescript - 如何将 NestJS 配置注入(inject) TypeORM 实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60287525/