AWSを初めて使う人がAmplifyのセットアップを行うまで

#前提
・Node.js v10.x or later
・npm v5.x or later
・git v2.14.1 or later

versionの確認は各種コマンドで

```
$ node -v
```

#AWSのアカウント作成を行う
[AWSアカウント作成](https://portal.aws.amazon.com/billing/signup?redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start)

#AWS Amplify CLIのインストール
npm install -g @aws-amplify/cli

#Amplifyが使用するIAMユーザーを新規作成する
1.amplify configure
2.そのままEnter
3.リージョンの選択
東京なので「ap-northeast-1」を選択
（※）公式のチュートリアルはus-east-1になっているので注意
4.「user name:」に何も入力せず、そのままEnterでOK

```
C:\Users\shibu>amplify configure
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:  amplify-rKF1w
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&accessKey&userNames=amplify-rKF1w&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess
Press Enter to continue
```

5.IAMユーザーを作成するための画面が立ち上がる
・ユーザー名「amplify-XXXXX(ランダム文字列)」
→好きなのに変える
・アクセスの種類「プログラムによるアクセスのみ許可」

##アクセス権限の設定
AdministratorAccessが選択されているハズ
一旦、このままでOK

##タグの設定
いまは必要ないのでそのまま「確認」押下

→確認して問題なければそのままユーザー作成

#Amplifyが使用するAWSアカウント情報の設定
1.「Press Enter to continue」となっているハズなのでEnter押下
2.ユーザー作成後の画面に表示されているアクセスキーIDを入力
3.同様にシークレットアクセスキーを入力
4.ローカルマシンに保存されるAWSプロファイル情報の名前を設定（任意でOK）

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

Successfully set up the new user.
```

#プロジェクトの作成
プロジェクト内に以下の各ファイルを作成

・package.json
・index.html
・webpack.config.js
・src/app.js

```
touch package.json index.html webpack.config.js src/app.js
```

以下をpackage.jsonファイルに追加

```
{
  "name": "amplify-js-app",
  "version": "1.0.0",
  "description": "Amplify JavaScript Example",
  "dependencies": {
    "@aws-amplify/api": "latest",
    "@aws-amplify/pubsub": "latest"
  },
  "devDependencies": {
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "copy-webpack-plugin": "^4.5.2",
    "webpack-dev-server": "^3.1.5"
  },
  "scripts": {
    "start": "webpack && webpack-dev-server --mode development",
    "build": "webpack"
  }
}
```

ローカル開発の依存関係をインストール

```
npm install
```

以下をindex.htmlに追加

```
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Amplify Framework</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            html, body { font-family: "Amazon Ember", "Helvetica", "sans-serif"; margin: 0; }
            a { color: #FF9900; }
            h1 { font-weight: 300; }
            .app { width: 100%; }
            .app-header { color: white; text-align: center; background: linear-gradient(30deg, #f90 55%, #FFC300); width: 100%; margin: 0 0 1em 0; padding: 3em 0 3em 0; box-shadow: 1px 2px 4px rgba(0, 0, 0, .3); }
            .app-logo { width: 126px; margin: 0 auto; }
            .app-body { width: 400px; margin: 0 auto; text-align: center; }
            .app-body button { background-color: #FF9900; font-size: 14px; color: white; text-transform: uppercase; padding: 1em; border: none; }
            .app-body button:hover { opacity: 0.8; }
        </style>
    </head>
    <body>
        <div class="app">
            <div class="app-header">
                <div class="app-logo">
                    <img src="https://aws-amplify.github.io/images/Logos/Amplify-Logo-White.svg" alt="AWS Amplify" />
                </div>
                <h1>Welcome to the Amplify Framework</h1>
            </div>
            <div class="app-body">
                <button id="MutationEventButton">Add data</button>
                <div id="MutationResult"></div>
                <div id="QueryResult"></div>
                <div id="SubscriptionResult"></div>
            </div>
        </div>
        <script src="main.bundle.js"></script>
    </body>
</html>
```

以下をwebpack.config.jsに追加

```
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const path = require('path');

module.exports = {
    mode: 'development',
    entry: './src/app.js',
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        contentBase: './dist',
        overlay: true,
        hot: true
    },
    plugins: [
        new CopyWebpackPlugin(['index.html']),
        new webpack.HotModuleReplacementPlugin()
    ]
};
```

アプリケーションを実行する

```
npm start
```

ブラウザからhttp：// localhost：8080へ移動
（※）この時点でADD DATAはまだ機能しないでOKです

#バックエンドのセットアップ
Amplifyを初期化して、アプリに関する情報の入力を行う

```
C:\Users\shibu\Desktop\amplify_nineteen>amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project nineteen
? Enter a name for the environment nineteen
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using none
? Source Directory Path:  src
? Distribution Directory Path: dist
? Build Command:  npm build
? Start Command: npm start
Using default provider  awscloudformation

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use shibuya_r
Adding backend environment nineteen to AWS Amplify Console app: d26bxlwur7bdpr
\ Initializing project in the cloud...

CREATE_IN_PROGRESS UnauthRole                       AWS::IAM::Role             Sun May 03 2020 21:07:32 GMT+0900 (GMT+09:00) Resource creation Initiated
CREATE_IN_PROGRESS AuthRole                         AWS::IAM::Role             Sun May 03 2020 21:07:31 GMT+0900 (GMT+09:00) Resource creation Initiated
CREATE_IN_PROGRESS UnauthRole                       AWS::IAM::Role             Sun May 03 2020 21:07:31 GMT+0900 (GMT+09:00)
CREATE_IN_PROGRESS DeploymentBucket                 AWS::S3::Bucket            Sun May 03 2020 21:07:31 GMT+0900 (GMT+09:00)
CREATE_IN_PROGRESS AuthRole                         AWS::IAM::Role             Sun May 03 2020 21:07:30 GMT+0900 (GMT+09:00)
CREATE_IN_PROGRESS amplify-nineteen-nineteen-210705 AWS::CloudFormation::Stack Sun May 03 2020 21:07:27 GMT+0900 (GMT+09:00) User Initiated
| Initializing project in the cloud...

CREATE_IN_PROGRESS DeploymentBucket AWS::S3::Bucket Sun May 03 2020 21:07:33 GMT+0900 (GMT+09:00) Resource creation Initiated
| Initializing project in the cloud...

CREATE_COMPLETE UnauthRole AWS::IAM::Role Sun May 03 2020 21:07:49 GMT+0900 (GMT+09:00)
CREATE_COMPLETE AuthRole   AWS::IAM::Role Sun May 03 2020 21:07:48 GMT+0900 (GMT+09:00)
/ Initializing project in the cloud...

CREATE_COMPLETE amplify-nineteen-nineteen-210705 AWS::CloudFormation::Stack Sun May 03 2020 21:07:57 GMT+0900 (GMT+09:00)
CREATE_COMPLETE DeploymentBucket                 AWS::S3::Bucket            Sun May 03 2020 21:07:54 GMT+0900 (GMT+09:00)
√ Successfully created initial AWS cloud resources for deployments.
√ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add <category>" will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything
```

ここまでAWS Amplifyコンソールでクラウドプロジェクトが作成され、amplifyコンソールを実行してアクセスできるようになる

#GraphQL API(Amazon DynamoDB)との接続
1.GraphQL APIの作成
アプリケーションディレクトリのルートから次のコマンドを実行

```
amplify add api
```

各種設定、今回は基本的にデフォルトで

```
C:\Users\shibu\Desktop\amplify_nineteen>amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: nineteenapi
? Choose the default authorization type for the API API key
? Enter a description for the API key: demo
? 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
? Do you want a guided schema creation? Yes
? What best describes your project: Single object with fields (e.g., “Todo” with ID, name, description)
? Do you want to edit the schema now? Yes
Please edit the file in your editor: C:\Users\shibu\Desktop\amplify_nineteen\amplify\backend/api/nineteenapi/schema.graphql
```

スキーマが正常にコンパイルされればOK
以下メッセージが表示されるはず

```
GraphQL schema compiled successfully

Edit your schema at C:\Users\shibu\Desktop\amplify_nineteen\amplify\backend\api\nineteenapi\schema.graphql or place .graphql files in a directory at C:\Users\shibu\Desktop\amplify_nineteen\amplify\backend\api\nineteenapi\schema
Successfully added resource nineteenapi 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
```

GraphQLスキーマをテキストエディタで開く
パスは以下
amplify/backend/api/nienteenapi/schema.graphql

2.作成したAPIをクラウドにpushしてデプロイできるようにする
以下コマンドの実行(さっきaddしたapiがpushされる)

```
amplify push
```
各種設定はこちら

```
? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/test.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
```

フロントエンドをAPIに接続する
Amplify.configure（）でライブラリを構成し、
API.graphql（）を使用してデータを変更してデータベースにデータを追加

#参考
[AWS Amplify CLIの使い方〜インストールから初期セットアップまで〜](https://qiita.com/Junpei_Takagi/items/f2bc567761880471fd54)
[Tutorial-Amazon Amplify Docs](https://docs.amplify.aws/start/getting-started/installation/q/integration/js#option-1-watch-the-video-guide)
[サーバーレスチュートリアル: フロントエンドでバックエンドをデプロイする](https://docs.aws.amazon.com/ja_jp/amplify/latest/userguide/deploy-backend.html)