当前位置: 首页 > 后端技术 > Node.js

Nestjs以monorepo模式开启项目之旅(一):使用cli初始构建项目并添加日志模块

时间:2023-04-04 00:08:43 Node.js

Nestjs以monorepo模式开启项目之旅(一)monorepo模式见官网创建项目nestnfullstackone创建一个子项目nestgappadminadmin是一个项目名创建一个符合javaspring的数据库,以mysql为数据库表结构如下:uuidvarcharkeyprimarynamevarcharsexintcreate_timedateupdate_timedate创建一个dblibrarynestglibdb因为db库是公共的,不限于某个子项目,因此从'typeorm'创建模型类libs/db/src/model/student.model.tsimport{Entity,PrimaryColumn,Column};@Entity({name:'student'})exportclassStudent{@PrimaryColumn()uuid:string@Column()name:string@Column()sex:number@Column({name:'create_time'})createTime:Date@Column({name:'update_time'})updateTime:Date}here使用mysql和typeorm库yarnaddmysql@nestjs/typeormtypeormmodifydbmoduleclasslibs/db/src/db.module.tsimport{Module}from'@nestjs/common';从'./db.import{DbService}服务';从'@nestjs/typeorm'导入{TypeOrmModule}从'./model/student.model'导入{学生};从'typeorm'导入{连接};常量models=TypeOrmModule.forFeature([Student])@Module({imports:[TypeOrmModule.forRoot({type:'mysql',host:'localhost',port:3306,username:'root',password:'123',database:'nestjs',entities:[Student],//引入学生实体类synchronize:true}),models],providers:[DbService],exports:[DbService,models],})exportclassDbModule{constructor(privatereadonlyconnection:Connection){}}创建学生模块在db中创建student.model后,在admin子项目中创建学生的controllerservice和mudlenestgcostudentnestgmostudentnestgsstudent学生创建后,nest将修改应用程序。module,即根模块,如下:imports:[DbModule,StudentModule,],nest通过imports关联几个子模块。也可以说子模块创建后,必须在根模块中注册控制器。基本上,它只负责简单的逻辑,如下:admin/src/student/student.controller.tsimport{Controller,Get,Param}from'@nestjs/common';import{StudentService}from'./student.service';@Controller('student')导出类StudentController{构造函数(私有读lystudentService:StudentService){}@Get()findAll(){returnthis.studentService.findAll();}@Get(':id')findById(@Param('id')id){返回this.studentService。findById(id);}}Controller负责注入学生服务service的依赖逻辑部分。首先,你要操作数据库,就得靠db模块constructor(@InjectRepository(Student)privatereadonlystudentRepository:Repository){}的注入完成,如下:import{Injectable}from'@nestjs/普通';从“@nestjs/typeorm”导入{InjectRepository};从“@app/db/model/student.model”导入{Student};从“typeorm”导入{Repository};从“@app/logger”导入{LoggerService};@Injectable()exportclassStudentService{constructor(@InjectRepository(Student)privatereadonlystudentRepository:Repository){}findAll(){returnthis.studentRepository.find();}findById(uuid:string){returnthis.studentRepository.findOne({where:{uuid}});}}运行进入项目文件夹,运行admin子项目neststart-wadminbrowser或者postman输入http://localhost:3000/student添加日志模块nestjs为渐进式架构,必须是Functions才可以一块一块地添加。创建日志模块nestgliblogger修改logger.service.tsimport{Injectable,Logger}from'@nestjs/common';@Injectable()exportclassLoggerServiceextendsLogger{}在需要logger模块的地方引入imports:[DbModule,LoggerModule,StudentModule,],在需要的地方先依赖注入再使用,如下:constructor(@InjectRepository(Student)privatereadonlystudentRepository:Repository,privatereadonlylogger:LoggerService){}findById(uuid:string){this.logger.log(`studentfindById:param->${uuid}`);返回this.studentRepository.findOne({where:{uuid}});}配置logger需要在main.ts类中过滤的级别有这些选项'log','error','warn','debug','verbose'asyncfunctionbootstrap(){constapp=awaitNestFactory.create(AppModule,{logger:['error','warn','log']});等待应用程序。听(3000);}引导程序();