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

订阅

订阅只是另一种GraphQL操作类型,如Query和Mutation。它允许在双向传输层上创建实时订阅,主要通过websockets。在此处阅读有关订阅的更多信息。以下是commentAdded订阅示例,直接从官方Apollo文档中复制并粘贴:

代码语言:javascript
复制
Subscription: {
  commentAdded: {
    subscribe: () => pubSub.asyncIterator('commentAdded')
  }
}

注意pubsub是一个PubSub类的实例。

为了在Nest中创建一个等价的订阅,我们将使用@Subscription()装饰器。让我们AuthorResolver在解析器部分扩展我们的用法。

代码语言:javascript
复制
const pubSub = new PubSub();

@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);
  }

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

  @Subscription()
  commentAdded() {
    return {
      subscribe: () => pubSub.asyncIterator('commentAdded'),
    };
  }
}

我们PubSub在这里使用了一个本地实例。相反,我们应该定义PubSub提供者,通过构造函数(使用@Inject()装饰器)注入它,并在整个应用程序中重用它。

为了启用订阅,我们必须将installSubscriptionHandlers属性设置为true

代码语言:javascript
复制
GraphQLModule.forRoot({
  typePaths: ['./**/*.graphql'],
  installSubscriptionHandlers: true,
})

要自定义订阅服务器(例如,更改端口),您可以使用subscriptions属性。

类型定义

最后一步是更新类型定义文件。

代码语言: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 Comment {
  id: String
  content: String
}

type Subscription {
  commentAdded(repoFullName: String!): Comment
}

做得好。我们创建了一个commentAdded(repoFullName: String!): Comment订阅。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com