Subscriptions
Subscription은 Query 및 Mutation과 같은 또 다른 GraphQL 작업 유형입니다. 양방향 전송 계층, 주로 웹 소켓을 통해 실시간 구독을 생성할 수 있습니다. Subscription에 대한 자세한 내용은 여기 를 참조하십시오. 아래는 공식 Apollo 문서에서 직접 복사 한 commentAdded
구독 예제입니다.
Copy Subscription : {
commentAdded : {
subscribe : () => pubSub .asyncIterator ( 'commentAdded' );
}
}
warning 알림 pubsub
는 PubSub
클래스의 인스턴스입니다. 자세한 내용은 여기 를 참조하십시오.
Schema first
Nest에서 동등한 구독을 만들려면 @Subscription()
데코레이터를 사용합니다.
Copy 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 pubSub .asyncIterator ( 'commentAdded' );
}
}
컨텍스트와 인수를 기반으로 특정 이벤트를 필터링하기 위해 filter
속성을 설정할 수 있습니다.
Copy @Subscription('commentAdded', {
filter: (payload, variables) =>
payload.commentAdded.repositoryName === variables.repoFullName,
})
commentAdded() {
return pubSub.asyncIterator('commentAdded');
}
게시된 페이로드를 변경하려면 resolve
함수를 사용할 수 있습니다.
Copy @Subscription('commentAdded', {
resolve: value => value,
})
commentAdded() {
return pubSub.asyncIterator('commentAdded');
}
Type definitions
마지막 단계는 유형 정의 파일을 업데이트하는 것입니다.
Copy 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
가입을 만들었습니다. 전체 샘플 구현은 여기 에서 찾을 수 있습니다.
Code first
클래스 우선 접근 방식을 사용하여 구독을 만들려면 @Subscription()
데코레이터를 사용합니다.
Copy const pubSub = new PubSub();
@Resolver('Author')
export class AuthorResolver {
constructor(
private readonly authorsService: AuthorsService,
private readonly postsService: PostsService,
) {}
@Query(returns => Author, { name: 'author' })
async getAuthor(@Args({ name: 'id', type: () => Int }) 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(returns => Comment)
commentAdded() {
return pubSub.asyncIterator('commentAdded');
}
}
컨텍스트와 인수를 기반으로 특정 이벤트를 필터링하기 위해 filter
속성을 설정할 수 있습니다.
Copy @Subscription(returns => Comment, {
filter: (payload, variables) =>
payload.commentAdded.repositoryName === variables.repoFullName,
})
commentAdded() {
return pubSub.asyncIterator('commentAdded');
}
게시된 페이로드를 변경하려면resolve
함수를 사용할 수 있습니다.
Copy @Subscription(returns => Comment, {
resolve: value => value,
})
commentAdded() {
return pubSub.asyncIterator('commentAdded');
}
PubSub
여기서는 로컬 PubSub
인스턴스를 사용했습니다. 대신, PubSub
를 공급자 로 정의하고 생성자 (@inject()
데코레이터를 사용하여)를 통해 주입한 다음 전체 애플리케이션에서 재 사용해야 합니다. Nest 사용자 지정 공급자 여기 에 대한 자세한 내용을 읽을 수 있습니다.
Copy {
provide: 'PUB_SUB',
useValue: new PubSub(),
}
Module
Subscription을 가능하게하려면 installSubscriptionHandlers
속성을 true
로 설정해야합니다.
Copy GraphQLModule.forRoot({
typePaths: ['./**/*.graphql'],
installSubscriptionHandlers: true,
}),
Subscription 서버 (예 : 포트 변경)를 사용자 정의하려면 subscriptions
속성을 사용하십시오 (여기 ).