首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

突变

在GraphQL中,为了修改服务器端数据,我们使用了突变(在这里阅读更多)a。官方的Apollo文档共享一个upvotePost()变异示例。该突变允许增加后votes属性值。为了在Nest中创建等效变异,我们将使用@Mutation()装饰器。让我们AuthorResolver在上一节中扩展我们的用法(参见解析器)。

代码语言:javascript
复制
@Resolver('Author')
export class AuthorResolver {
  constructor(
    private readonly authorsService: AuthorsService,
    private readonly postsService: PostsService,
  ) {}

  @Query('author')
  async getAuthor(@Args('id') id: number) {
    return await this.authorsService.findOneById(id);
  }

  @Mutation()
  async upvotePost(@Args('postId') postId: number) {
    return await this.postsService.upvoteById({ id: postId });
  }

  @ResolveProperty('posts')
  async getPosts(@Parent() { id }) {
    return await this.postsService.findAll({ authorId: id });
  }
}

请注意,我们假设业务逻辑已移至PostsService(分别查询post和incrementing votes属性)。

类型定义

最后一步是将我们的变异添加到现有的类型定义中。

代码语言:javascript
复制
type Author {
  id: Int!
  firstName: String
  lastName: String
  posts: [Post]
}

type Post {
  id: Int!
  title: String
  votes: Int
}

type Query {
  author(id: Int!): Author
}

type Mutation {
  upvotePost(postId: Int!): Post
}

upvotePost(postId: Int!): Post现在的突变应该可用。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com