Amplifyもう一度やっていく

今度は公式でツールの使い方を覚えてからQiita記事を

AWS の開始方法 React アプリケーションの構築 AWS Amplify を使用してシンプルなウェブアプリケーションを作成する https://aws.amazon.com/jp/getting-started/hands-on/build-react-app-amplify-graphql/module-one/?e=gs2020&p=build-a-react-app-intro

最終的にこっちをやりたい
【爆速】React+Amplify+AppSyncでリアルタイム掲示板アプリを15分で作り上げる 〜これが最高のDeveloper Experienceだ〜 https://qiita.com/G-awa/items/a5b2cc7017b1eceeb002

npxは素晴らしい

$ npx create-react-app amplifyapp
~~
Success! Created amplifyapp at /home/sh3eys/git/testapp_20210506/amplifyapp
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd amplifyapp
  npm start

Happy hacking!

一発でstartが成功するだけで嬉しいという つくずく create-react-app は素晴らしいと感心する

$ npm start

https://aws.amazon.com/jp/getting-started/hands-on/build-react-app-amplify-graphql/module-one/?e=gs2020&p=build-a-react-app-intro
あとはここに沿ってコンソール操作してくだけでいい 最後の自動ビルドから検証までが裏で走っててホスティングされたReactAppが更新されるまで結構なラグがある 空気読んで待てばいい

続いてこちらを。npmでインストールしてやってるところはnpxに置き換えて使っていく方針に
【爆速】React+Amplify+AppSyncでリアルタイム掲示板アプリを15分で作り上げる 〜これが最高のDeveloper Experienceだ〜 https://qiita.com/G-awa/items/a5b2cc7017b1eceeb002

yarnもnpm startで代わりが利くので準備しない

ただ全部うまくいくわけじゃなかった当たり前だがamplifyコマンドはセットアップ必要そう

sh3eys@DESKTOP-VUKTP3T:~/git/boardapp$ npx amplify init

┌──────────────────────────────────────────────────────────┐
│                 npm update check failed                  │
│           Try running with sudo or get access            │
│           to the local update config store via           │
│ sudo chown -R $USER:$(id -gn $USER) /home/sh3eys/.config │
└──────────────────────────────────────────────────────────┘
npx: installed 1 in 1.424s
command not found: amplify

適当に探してこれがよさそうだったのでこれに従ってやってみる
https://docs.amplify.aws/start/getting-started/installation/q/integration/react#option-2-follow-the-instructions

sudo無しだとエラーして-gでインストールできなさそうだった

$ sudo npm install -g @aws-amplify/cli
...
..
.
----------------------------------------
Successfully installed the Amplify CLI
----------------------------------------

IAMユーザーのconfigure ちゃんと見てない

sh3eys@DESKTOP-VUKTP3T:~/git/boardapp$ amplify configure
Initializing new Amplify CLI version...
Done initializing new version.
Scanning for plugins...
Plugin scan successful
Follow these steps to set up access to your AWS account:

Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue

Specify the AWS Region
? region:  ap-northeast-1
Specify the username of the new IAM user:
? user name:  sh3eys-boardapp-admin
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=ap-northeast-1#/users$new?step=final&accessKey&userNames=sh3eys-boardapp-admin&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess
Press Enter to continue

Enter the access key of the newly created user:
? accessKeyId:  ********************
? secretAccessKey:  ****************************************
This would update/create the AWS Profile in your local machine
? Profile Name:  default

Successfully set up the new user.
┌──────────────────────────────────────────────────────────┐
│           @aws-amplify/cli update check failed           │
│           Try running with sudo or get access            │
│           to the local update config store via           │
│ sudo chown -R $USER:$(id -gn $USER) /home/sh3eys/.config │
└──────────────────────────────────────────────────────────┘

initはこう 最初から良さそうな選択肢を提案してくれるのAmazonらしくて好き ここもほぼノールックで進めた

sh3eys@DESKTOP-VUKTP3T:~/git/boardapp$ amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project boardapp
The following configuration will be applied:

Project information
| Name: boardapp
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: react
| Source Directory Path: src
| Distribution Directory Path: build
| Build Command: npm run-script build
| Start Command: npm run-script start

API作成はこうなった 少し質問おおい わけわかんないけど適当に

sh3eys@DESKTOP-VUKTP3T:~/git/boardapp$ amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: boardapp
? Choose the default authorization type for the API API key
? Enter a description for the API key: boardapp
? After how many days from now the API key should expire (1-365): 7
? Do you want to configure advanced settings for the GraphQL API No, I am done.
? Do you have an annotated GraphQL schema? No
? Choose a schema template: One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)

The following types do not have '@auth' enabled. Consider using @auth with @model
         - Blog
         - Post
         - Comment
Learn more about @auth here: https://docs.amplify.aws/cli/graphql-transformer/auth


GraphQL schema compiled successfully.

Edit your schema at /home/sh3eys/git/boardapp/amplify/backend/api/boardapp/schema.graphql or place .graphql files in a directory at /home/sh3eys/git/boardapp/amplify/backend/api/boardapp/schema
? Do you want to edit the schema now? No
Successfully added resource boardapp locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

┌──────────────────────────────────────────────────────────┐
│           @aws-amplify/cli update check failed           │
│           Try running with sudo or get access            │
│           to the local update config store via           │
│ sudo chown -R $USER:$(id -gn $USER) /home/sh3eys/.config │
└──────────────────────────────────────────────────────────┘

なんかテンプレから生成したスキーマは記事で紹介されてるものと変わっちゃったけどまあ気にせずこのままいく

sh3eys@DESKTOP-VUKTP3T:~/git/boardapp$ cat amplify/backend/api/boardapp/schema.graphql
type Blog @model {
  id: ID!
  name: String!
  posts: [Post] @connection(keyName: "byBlog", fields: ["id"])
}

type Post @model @key(name: "byBlog", fields: ["blogID"]) {
  id: ID!
  title: String!
  blogID: ID!
  blog: Blog @connection(fields: ["blogID"])
  comments: [Comment] @connection(keyName: "byPost", fields: ["id"])
}

type Comment @model @key(name: "byPost", fields: ["postID", "content"]) {
  id: ID!
  postID: ID!
  post: Post @connection(fields: ["postID"])
  content: String!
}

とにかくnpxで叩いて楽する

$ npx yarn add aws-amplify aws-amplify-react

とりあえずlocalで動かして様子見していこうと思ったらエラー

npm start

3959db6d41680d4791f5d74b7ca506f5.png Consoleデバッグでこう返ってくるので登録処理のメソッドなんとかしなあかんぽい。デバッグし易く手順を書いてくれるの玄人感あって頼もしい

message: "The variables input contains a field name 'content' that is not defined for input object type 'CreatePostInput' "

次こうなった

"The variables input contains a field name 'comments' that is not defined for input object type 'CreatePostInput' "

ここで大嵌りした。冷静に考えてinput object typeを調べればよかったけどソースそこまでじっくり読み込んでもなかったからあてずっぽうで mutation.js 見ながら色々試してこれらがダメだった

"The variables input contains a field name 'blog' that is not defined for input object type 'CreatePostInput' "

"The variables input contains a field name 'postCommentsItemsContent' that is not defined for input object type 'CreatePostInput' "

"The variables input contains a field name 'commentsItemsContent' that is not defined for input object type 'CreatePostInput' "

ここまで来てもういいかと諦めて content に相当する投稿を外して title だけを CreatePostInputのmutationへ入れようとして以下のエラーメッセージを得たところでやっと input type定義が mutation.js にある記述じゃない別のところで書かれてるやつだと気づいた

"Variable 'input' has coerced Null value for NonNull type 'ID!'"

GraphQL全般がこれなのかな?ちょっとよくわからんけど、結局は schema.js へ定義があってDynamoDB側へinput object定義されてるようだった

DynamoDBにもレコードが登録されています。 これやっとできたすごい辛かったinput object typeの定義を探すのに手間取ってしまった.. ここに書かれてあった

src/graphql/schema.json
~/git/boardapp$ grep -A 40 CreatePostInput src/graphql/schema.json  | tail -41
        "name" : "CreatePostInput",
        "description" : null,
        "fields" : null,
        "inputFields" : [ {
          "name" : "id",
          "description" : null,
          "type" : {
            "kind" : "SCALAR",
            "name" : "ID",
            "ofType" : null
          },
          "defaultValue" : null
        }, {
          "name" : "title",
          "description" : null,
          "type" : {
            "kind" : "NON_NULL",
            "name" : null,
            "ofType" : {
              "kind" : "SCALAR",
              "name" : "String",
              "ofType" : null
            }
          },
          "defaultValue" : null
        }, {
          "name" : "blogID",
          "description" : null,
          "type" : {
            "kind" : "NON_NULL",
            "name" : null,
            "ofType" : {
              "kind" : "SCALAR",
              "name" : "ID",
              "ofType" : null
            }
          },
          "defaultValue" : null
        } ],

e6497e0ce7c89470ad1ec3ae82d0713d.png

とここまでうまくいったけど、最後に subscription 更新を取得して画面描画する がうまくいかない というか最初から投稿内容がrenderされてない画面にtitleへ入れた文字が返ってきてないし

最後ここ入れ忘れてた。renderへこれ入れたらとりあえず動くようになった

あと、this.state.postsの内容を表示させる処理が、App.jsのrender関数に無いようなので、これも追加が必要だと思います。 雑ですが、こんな感じで追加して、画面に反映されるようになりました。

いったんとりあえず動いてるからまあいいか チャットアプリを作っていきたいのでここからまずはAPサーバーとして体裁整えていく感じで

と思ったら未だamplify pushしてなかったしgitコミットすらしてなかった… ここで力尽きた