Mutations
Mutations
GraphQL์์ ์๋ฒ ์ธก ๋ฐ์ดํฐ๋ฅผ ์์ ํ๊ธฐ ์ํด Mutaion์ ์ฌ์ฉํฉ๋๋ค (๋ ์์ธํ ๋ด์ฉ์ ์ฌ๊ธฐ). ๊ณต์์ ์ธ Apollo ๋ฌธ์๋ upvotePost() Mutation ์์ ๋ฅผ ๊ณต์ ํฉ๋๋ค. ์ด Mutation์ ํฌ์คํธ votes์์ฑ ๊ฐ์ ์ฆ๊ฐ์ํต๋๋ค. Nest์์ ๋๋ฑํ ๋์ฐ๋ณ์ด๋ฅผ ๋ง๋ค๊ธฐ ์ํด ์ฐ๋ฆฌ๋@Mutation()๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ  ๊ฒ์
๋๋ค.
Schema first
์ด์  ์น์
์์ ์ฌ์ฉํ AuthorResolver๋ฅผ ํ์ฅ ํด ๋ณด์ (resolvers ์ฐธ์กฐ).
@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 (ํฌ์คํธ ์กฐํ ๋ฐ ํฌํ) ์์ฑ์ผ๋ก ์ด๋๋์๋ค๊ณ  ๊ฐ์ ํ๋ค.
Type definitions
๋ง์ง๋ง ๋จ๊ณ๋ ๊ธฐ์กด ์ ํ ์ ์์ ๋ฎคํ ์ด์ ์ ์ถ๊ฐํ๋ ๊ฒ์ ๋๋ค.
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 ๋ณ์ด๊ฐ ๊ฐ๋ฅํด์ผํฉ๋๋ค.
Code first
์ด์  ์น์
์์ ์ฌ์ฉ ๋ AuthorResolver์ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ ์ถ๊ฐํด ๋ณด์ (resolvers ์ฐธ์กฐ).
@Resolver(of => 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);
  }
  @Mutation(returns => Post)
  async upvotePost(@Args({ name: 'postId', type: () => Int }) postId: number) {
    return await this.postsService.upvoteById({ id: postId });
  }
  @ResolveProperty('posts')
  async getPosts(@Parent() author) {
    const { id } = author;
    return await this.postsService.findAll({ authorId: id });
  }
}upvotePost()๋postId (Int)๋ฅผ ์
๋ ฅ ๋งค๊ฐ ๋ณ์๋ก ๋ฐ์์ ์
๋ฐ์ดํธ ๋ Post ์ํฐํฐ๋ฅผ ๋ฐํํฉ๋๋ค. resolvers ์น์
์์์ ๊ฐ์ ์ด์ ๋ก ์์๋๋ ์ ํ์ ๋ช
์์ ์ผ๋ก ์ค์ ํด์ผ ํฉ๋๋ค.
๋ฎคํ ์ด์ ์ด ๊ฐ์ฒด๋ฅผ ๋งค๊ฐ ๋ณ์๋ก ๊ฐ์ ธ์์ผ ํ๋ ๊ฒฝ์ฐ ์ ๋ ฅ ์ ํ์ ๋ง๋ค ์ ์์ต๋๋ค.
@InputType()
export class UpvotePostInput {
  @Field() postId: number;
}info ํํธ
@InputType()๊ณผ@Field()๋ ๋ชจ๋ type-graphql ํจํค์ง์์ ๊ฐ์ ธ์ต๋๋ค.
๊ทธ๋ฐ ๋ค์ ๋ฆฌ์กธ๋ฒ ํด๋์ค์์ ์ฌ์ฉํ์ญ์์ค.
@Mutation(returns => Post)
async upvotePost(
  @Args('upvotePostData') upvotePostData: UpvotePostInput,
) {}Last updated
Was this helpful?