如何将NestJS配置注入TypeORM实体



让我们简化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;
}
}
}

我需要用NestJS的配置(ConfigService中的命名空间(替换config.auth.password.secret

export default registerAs('app', () => {
return {
password: {
secret: process.env.AUTH_PASSWORD_SECRET,
}
};
});

,但是实体不是NestJS结构的一部分,所以我不能像往常一样注入它。

如何在TypeORM实体中实现NestJS配置?

我也需要这个,并想出了解决方法。您不能将配置注入Entity,正如前面所说的那样。

我想出了一个解决方案,可以导出实体中需要的具有配置值的对象:

初始化应用程序内配置模块:

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;
}

实体不是NestJS中可注入提供者的一部分,因此本质上这是不可能的。但是,您可以将其作为服务代码的一部分,并在插入/更新之前进行密码哈希。

@Entity()
export class User extends BaseDatabaseEntity {
@Column({
length: 255,
})
public firstName!: string;
@Column({
length: 60,
transformer: new PasswordTransformer(new ConfigService())
})
@Exclude()
public password: string;
}
export class PasswordTransformer implements ValueTransformer {
constructor(private config: ConfigService) {}
from(value: string): string {
return value;
}
to(value: string): string {
return hashSync(
this.password + this.config.get('AUTH_PASSWORD_SECRET'),
genSaltSync(),
);
}
}

最新更新