Nestjs+GraphQL搭建服务前面我们介绍了GraphQL的概念和基础知识,本文记录下使用Nestjs+GraphQL搭建Node服务。安装npmi--save@nestjs/graphqlgraphql-toolsgraphqlapollo-server-expressregister//app.module.tsimport{Module}from'@nestjs/common';从'@nestjs/graphql'导入{GraphQLModule};import{ConfigModule,ConfigService}from'nestjs-config';@Module({imports:[ConfigModule.load(path.resolve(__dirname,'config','**/!(*.d).{ts,js}')),GraphQLModule.forRootAsync({imports:[ConfigModule],useFactory:(config:ConfigService)=>config.get('graphql'),inject:[ConfigService],})],})导出类ApplicationModule{}//src/config/graphql.tsimport*aspathfrom'path';exportdefault{autoSchemaFile:path.join(process.cwd(),'src/schema.gql'),//最后生成的`Schema文件,不可修改`installSubscriptionHandlers:true,//启用订阅};启动项目,访问http://localhost:3000/graphql,我们可以看到graphql页面。编写服务端逻辑接下来我们注册一个作者模块,目录结构如下://author.module.tsimport{Module}from'@nestjs/common';import{AuthorService}from'./author.service';import{AuthorResolver}from'./author.resolver';@Module({providers:[AuthorService,AuthorResolver]})exportclassAuthorModule{}//author.service.ts//这个文件用来写数据库等逻辑查询,我们专注于学习使用GraphQL,所以没有相关的Demoimport{Injectable}from'@nestjs/common';@Injectable()exportclassAuthorService{asyncfindOneById(){}}//author.resolver.tsimport{Args,Mutation,Query,Resolver,Subscription,ResolveField,Parent,Int}from'@nestjs/graphql';import{PubSub}来自'graphql-subscriptions';从'./models/author.model'导入{Author};从'./models/post.model'导入{Post};import{AuthorService}from'./author.service';//import{GetAuthorArgs}from'./dto/get-author.args';constpubSub=newPubSub();@Resolver(()=>Author)exportclassAuthorResolver{constructor(privateauthorsService:AuthorService){}//根据id查询作者信息@Query(returns=>Author,{name:'author',description:'通过id获取作者信息',nullable:false})asyncgetAuthor(@Args('id',{type:()=>Int,description:'authorid',nullable:false})id:number):Promise{//returnthis.authorsService.findOneById(id);return{id,firstName:'wu',lastName:'pat',};}//使用DTO接收参数//@Query(returns=>Author)//asyncgetAuthor(@Args()args:GetAuthorArgs){//returnthis.authorsService.findOneById(args);//}//修改作者信息@Mutation(returns=>Author,{name:'changeAuthor',description:'通过id更改作者信息',nullable:false})asyncchangeAuthor(@Args('id')id:number,@Args('firstName')firstName:string,@Args('lastName')lastName:string,):Promise{//返回this.authorsService.findOneById(ID);return{id,firstName,lastName,};}//解析帖子段落@ResolveField()asyncposts(@Parent()author:Author):Promise{const{id}=作者;//返回this.postsService.findAll({authorId:id});返回[{id:4,title:'hello',votes:2412,}];}//新帖子@Mutation(returns=>Post)asyncaddPost(){constnewPost={id:1,title:'Newpost'};//添加成功后通知更新awaitpubSub.publish('postAdded',{postAdded:newPost});返回新帖子;}//监控变化@Subscription(returns=>Post,{name:'postAdded',//filter:(payload,variables)=>payload.postAdded.title===variables.title,//过滤订阅//resolve(this:AuthorResolver,value){//修改payload参数//返回值;//}})asyncpostAdded(/*@Args('title')title:string*/){return(awaitpubSub.asyncIterator('添加后'));}}//author.model.tsimport{Field,Int,ObjectType}from'@nestjs/graphql';从'./post.model'导入{Post};@ObjectType({描述ion:'Authormodel'})exportclassAuthor{@Field(type=>Int,{description:'authorid'})id:number;@Field({nullable:true,description:'authorlastname'})firstName?:string;@Field({nullable:true,description:'作者姓名'})lastName?:string;//要声明数组的项(而不是数组本身)可为空,请设置可为空的属性Set'items'//如果数组及其项都可为空,则将可为空的设置为'itemsAndList'@Field(type=>[Post],{nullable:'items',description:'作者发表的文章'})posts:Post[];}//posts.model.tsimport{Field,Int,ObjectType}from'@nestjs/graphql';@ObjectType()exportclassPost{@Field(type=>Int)id:number;@Field()标题:字符串;@Field(type=>Int,{nullable:true})votes?:number;}上面的代码包括查询、更改和订阅类型。此时,我们会发现src中增加了一个文件schema.gql,这个文件是一个自动生成的类型文件:#--------------------------------------------------#此文件是自动生成的(请勿修改)#-------------------------------------------------------typePost{id:Int!标题:字符串!票数:我nt}"""Authormodel"""typeAuthor{"""Authorid"""id:Int!"""Authorlastname"""firstName:String"""Authorname"""lastName:String"""作者发表的文章"""posts:[Post]!}typeQuery{"""通过id获取作者信息"""author("""authorid"""id:Int!):Author!}typeMutation{"""通过id更改作者信息"""changeAuthor(lastName:String!,firstName:String!,id:Float!):Author!addPost:Post!}typeSubscription{postAdded:Post!}此时执行查询我们的服务已经启动,可以执行查询了#Wr??iteQUERYVARIABLES{"id":1}#Writeyourqueryormutationhere#Queryauthorinformationqueryauthor($id:Int!){alias:author(id:$id){id,firstName,posts{id,title}}}#修改作者信息mutationchangeAuthor{changeAuthor(id:3,firstName:"firstName"lastName:"lastName"){id,firstName,lastName}}#发布文章mutationaddPost{post:addPost{id,title}}#添加订阅postAdded{postAdded{id,title}}//自省查询queryschema{__schema{types{name}}}至此,我们的Nestjs+GraphQL服务搭建完成,给自己一个赞!