0
0

More than 1 year has passed since last update.

AmplifyでカスタムGraphQLクエリと型情報を生成する方法

Last updated at Posted at 2022-08-26

本記事を対象とする人

  • Web(React,Vueなど)でAmplify利用し、自動生成されるクエリでは足りなくなった

結論

  • graphqlconfig.ymlのincludesに指定しているディレクトリにファイルを作成する

解説

デフォルトで生成されるスキーマを元に説明します

~/amplify/backend/api/[project]/schema.graphql
type Blog @model {
  id: ID!
  name: String!
  posts: [Post] @hasMany
}

type Post @model {
  id: ID!
  title: String!
  blog: Blog @belongsTo
  comments: [Comment] @hasMany
}

type Comment @model {
  id: ID!
  post: Post @belongsTo
  content: String!
}
  • 例として、ブログに投稿されている記事のコメントを取得したい場合
~/src/graphql/customQueries.js
export const getBlogDetail = /* GraphQL */ `
  query GetBlogDetail($id: ID!) {
    getBlog(id: $id) {
      id
      name
      posts {
        items {
          id
          title
          createdAt
          updatedAt
          blogPostsId
          comments {
            items {
              id
              contents
            }
            nextToken
          }
        }
        nextToken
      }
      createdAt
      updatedAt
    }
  }
`;
  • 生成された型情報

注意点

  • amplify codegenした際に型生成される対象となるのは、
~/graphqlconfig.yml
projects:
  [project]:
    schemaPath: amplify/backend/api/[project]/build/schema.graphql
    includes:
      - src/graphql/**/*.js
    excludes:
      - ./amplify/**
    extensions:
      amplify:
        codeGenTarget: typescript
        generatedFileName: src/API.ts
        docsFilePath: src/graphql
extensions:
  amplify:
    version: 3

上記のファイルのincludesの部分です。
拡張子をtsなどに変えていると、型が何も生成されないので注意しましょう。

0
0
1

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