我正在将项目从expressjs更改为nestjs。
在express中,我在app.ts中默认添加了一个admin用户到数据库中。
像这样:
public async addDefaultAdmin() {
UserModel.find({ role: Roles.admin }).then(async (superAdmin) => {
if (superAdmin.length === 0) {
try {
const newUser = new UserModel({...});
await this.hashPassWord(newUser);
await newUser.save();
console.log("default admin successfully added.");
} catch (error: any) {
console.log(error);
}
}
});
}
我想知道如何在 NestJS 中做到这一点? NestJS或typeOrm有解决这个问题的方法吗?
您可能需要使用生命周期事件。 NestJS 在应用程序引导和关闭期间触发事件。
根据医生的说法,
onApplicationBootstrap()
活动可能对您的情况有帮助。
在所有模块初始化后但在侦听连接之前调用。
但是,NestJS 在应用程序开始监听后不会公开钩子,因此在这种情况下,您需要在服务器可以监听端口后立即在
bootstrap
函数内运行自定义函数。
伪代码如下:
// main.ts
import { User } from '/path/to/user.entity';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
...
await app.listen(3000);
let user = app.get(getRepositoryToken(User)); // You need to pass the entity file to typeorm
await addDefaultAdmin(user); // Pass the user model, and call the function
}
bootstrap();