authors.resolver.ts 2.1 KB
import {
  Args,
  Mutation,
  Query,
  Resolver,
  Subscription,
  ResolveField,
  Parent,
  Int,
} from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
import { Author } from './models/author.model';
import { Post } from './models/post.model';
import { AuthorsService } from './authors.service';
import { PostsService } from './posts.service';

const pubSub = new PubSub();

@Resolver(() => Author)
export class AuthorsResolver {
  constructor(
    private authorsService: AuthorsService,
    private postsService: PostsService,
  ) {}

  @Query((returns) => Author)
  async author(@Args('id', { type: () => Int }) id: number) {
    return this.authorsService.findOneById(id);
  }

  // 根据id查询作者信息
  @Query((returns) => Author, {
    name: 'author',
    description: 'get author info by id',
    nullable: false,
  })
  async getAuthor(
    @Args('id', {
      type: () => Int,
      description: 'author id',
      nullable: false,
    })
    id: number,
  ): Promise<any> {
    return {
      id,
      firstName: 'wu',
      lastName: 'pat',
    };
  }
  // 修改作者信息
  @Mutation((returns) => Author, {
    name: 'changeAuthor',
    description: 'change author info by id',
    nullable: false,
  })
  async changeAuthor(
    @Args('id') id: number,
    @Args('firstName') firstName: string,
    @Args('lastName') lastName: string,
  ): Promise<any> {
    return {
      id,
      firstName,
      lastName,
    };
  }
  // 解析posts字段
  @ResolveField()
  async posts(@Parent() author: Author): Promise<any> {
    const { id } = author;
    return [
      {
        id: 4,
        title: 'hello',
        votes: 2112,
      },
    ];
  }
  // 新增文章
  @Mutation((returns) => Post)
  async addPost() {
    const newPost = {
      id: 1,
      title: '新增文章',
    };
    // 新增成功后,通知更新
    await pubSub.publish('postAdded', { postAdded: newPost });
    return newPost;
  }

  // 监听变更
  @Subscription((returns) => Post, {
    name: 'postAdded',
  })
  async postAdded(/*@Args('title') title: string*/) {
    return pubSub.asyncIterator('postAdded');
  }
}