0
0

More than 1 year has passed since last update.

GraphQL サーバー構築(その2. Mutation の実装)

Last updated at Posted at 2022-12-30

Mutation の実装

前回

ローカルでGraphQL サーバー構築(その1. Apolloを利用したgraphqlサーバー立ち上げまで)

今回やること

  • mutation typeスキーマの定義
  • リゾルバの定義
  • playgroundでテスト

mutation typeスキーマの定義

index.ts
const typeDefs = `#graphql

 (略)

  type Mutation {
    addBook(title: String, author: String): Book
  }

`;

リゾルバの定義

index.ts
const resolvers = {
    ()

    Mutation: {
        addBook(parent, args: {title:string, author: string}){
            const book = {
                author: args.author,
                title: args.title,
            };
            books.push(book)
            return book;
        }
      }
};

playgroundでテスト

request
mutation addBookTest{
  addBook(author: "test", title: "title") {
    author,
    title
  }
}
response
{
  "data": {
    "addBook": {
      "author": "test",
      "title": "title"
    }
  }
}
  • bookが追加されていることを確認
request
query ExampleQuery {
  books {
    author
    title

  }
}
response
{
  "data": {
    "books": [
      {
        "author": "Kate Chopin",
        "title": "The Awakening"
      },
      {
        "author": "Paul Auster",
        "title": "City of Glass"
      },
      {
        "author": "test",
        "title": "title"
      },
      {
        "author": "test",
        "title": "title"
      }
    ]
  }
}
  • okです。

このやりたいこと

  • .graphqlファイルを利用したリファクタリング

  • graphql-codegenでTypeScriptの型定義を生成する
  • prismaとの連携
    参考: APOLLO DOCS
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0