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

使用NestJS开发Node.js应用

时间:2023-04-03 11:14:12 Node.js

NestJS最早成立于2017年1月,第一个正式版于2017年5月发布,是一个基于Express的使用TypeScript开发的后端框架。设计之初主要是为了解决开发Node.js应用时的架构问题,受到Angular的启发。在本文中,我将简要概述NestJS中的一些亮点。组件容器NestJS采用了组件容器的方式,每个组件都与其他组件解耦。当一个组件依赖另一个组件时,需要指定要使用的节点的依赖:import{Module}from'@nestjs/common';import{CatsController}from'./cats.controller';import{CatsService}from'./cats.service';import{OtherModule}from'../OtherModule';@Module({imports:[OtherModule],controllers:[CatsController],providers:[CatsService],})exportclassCatsModule{}依赖注入(DI)类似于Angular,也是采用依赖注入的设计模式开发的。在使用一个对象时,DI容器已经为你创建好了,不需要手动实例化来实现解耦://创建一个服务@Inject()exportclassTestService{publicfind(){return'helloworld';}}//创建一个controller@Controller()exportclassTestController{controller(privatereadonlytestService:TestService){}@Get()publicfindInfo(){returnthis.testService.find()}}以便TestController使用TestService服务,你只需要在创建模块时将其写成提供者:@Module({controllers:[TestController],providers:[TestService],})exportclassTestModule{}当然,你可以注入任何类@Inject()到该模块的控制器或服务的模块中using背后的实现是基于Decorator+ReflectMetadata。详见深入理解TypeScript-ReflectMetadata。细粒度中间件在使用Express的时候,我们会用到各种中间件,比如日志服务、超时拦截、权限校验等。在NestJS中,中间件功能分为Middleware、Filters、Pipes、Grards、Interceptors。例如,使用Filter来捕获和处理应用程序中抛出的错误:constresponse=ctx.getResponse();constrequest=ctx.getRequest();conststatus=exception.getStatus();//其他事情要做,比如日志响应.status(status).json({statusCode:status,timestamp:newDate().toISOString(),path:request.url,});}}使用拦截器拦截响应数据,使得返回的数据格式为{data:T}:import{Injectable,NestInterceptor,ExecutionContext}from'@nestjs/common';import{Observable}from'rxjs';从'rxjs/operators'导入{map};exportinterfaceResponse{data:T;}@Injectable()exportclassTransformInterceptorimplementsNestInterceptor>{intercept(context:ExecutionContext,调用$:Observable,):Observable>{return调用$.pipe(map(data=>({data})));使用Guards,当没有'admin'角色时,返回401:import{ReflectMetadata}from'@nestjs/common';exportconstRoles=(...roles:string[])=>ReflectMetadata('roles',roles);@Post()@Roles('admin')asynccreate(@Body()createCatDto:CreateCatDto){这个。猫服务。create(createCatDto);}由于类验证器和类转换器,数据验证非常简单://createDtoexportclassContentDto{@IsString()text:string}@Controller()exportclassTestController{controller(privatereadonlytestService:TestService){}@Get()publicfindInfo(@Param()param:ContentDto//use){returnthis.testService.find()}}当传入的参数文本不是字符串时,会出现400错误GraphQLGraphQL由facebook开发,被认为是一种革命性的API工具,因为它允许客户端在请求中指定他们想要的数据,而不像传统的REST,后者只能在后端进行预定义。NestJS包装了Apollo服务器,使其更易于在NestJS中使用。在Express中使用Apollo服务器时:constexpress=require('express');const{ApolloServer,gql}=require('apollo-server-express');//构造一个模式,使用GraphQL模式语言consttypeDefs=gql`typeQuery{hello:String}`;//为您的模式字段提供解析器函数constresolvers={Query:{hello:()=>'Helloworld!',},};constserver=newApolloServer({typeDefs,resolvers});constapp=express();server.applyMiddleware({app});constport=4000;app.listen({port},()=>console.log(`服务器准备在http://localhost:${port}${server.graphqlPath}`);在NestJS中使用:使用Decorator看起来更像TypeScript。除了上面列举的一些,NestJS实现微服务开发,配合TypeORM,Prisma等,这里不再展开。深入理解TypeScript的参考——ReflectMetadataEggVSNestJSNestJS官网