非常教程

Nest参考手册

GRAPHQL

订阅

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

Subscription: {
  commentAdded: {
    subscribe: () => pubSub.asyncIterator('commentAdded')
  }
}

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

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

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

GraphQLModule.forRoot({
  typePaths: ['./**/*.graphql'],
  installSubscriptionHandlers: true,
})

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

类型定义

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

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订阅。

Nest

Nest 是一个用于构建高效,可扩展的 Node.js 服务器端应用程序的框架

Nest目录

1.介绍
2.常见问题
3.CLI
4.方法
5.执行上下文
6.微服务
7.WEBSOCKETS
8.GRAPHQL
9.技术
10.基本内容
11.迁移指南