The source code for this blog is available on GitHub.

Blog.

Amplifyを学ぶ

Cover Image for Amplifyを学ぶ

合計時間:64時間 作業時間:2時間

Tutrial (React)

チュートリアルを行った。ログインとTodoリスト作成を実装するまでができる。 AWSのアカウントを作成して、nodemodulesをインストールして従ったら大体できた。 サーバーレスで認証周りまで面倒見てくれるのが凄い。 アプリケーションを置いて置けるの良いな。 SSGせずともいけるのが分かってよかった。 SSRを利用したプロジェクトも展開できるのかな。 面倒を見過ぎられて内部でどう動いているかの理解が出来ていないのが辛い。

管理画面の役割の確認。 サービスより、

  • AWS AppSync
  • AWS Amplify
  • IAM
  • Billing
  • AWS マネジメントコンソール

AWS AppSync

APIの管理を行っている。 dbへ保存したデータをrestかgraphQLで取得して利用できる。

AWS Amplify

開発環境の情報を管理している。 ホスティングしたドメインなどがまとめられている。 git pushしたら自動でbuildしてホスティングするまで面倒見てくれるっぽい。

IAM

アカウントの管理を行っている。

Billing

利用料を管理している。 一年間は無料だが、絶対忘れるだろうな。 一定以上額したら停止できる?っていう設定があった気がするので、それしておきたい。

AWS マネジメントコンソール

チュートリアルやハウトゥーを管理している。

AWS Amplify入門① / Storageについての解説

Reactのチュートリアルのおさらい。 メモアプリが作成できる。

Prerequisites

AWSのアカウントを作成する。

amplifyコマンドを実行するため、cliを導入する。

npm install -g @aws-amplify/cli

以下のコマンドで初期設定を行う。

amplify configure

もろもろ選択する。

Specify the AWS Region
? region:  # Your preferred region
Specify the username of the new IAM user:
? user name:  # User name for Amplify IAM user
Complete the user creation using the AWS console

途中でブラウザへ飛ばされ、アカウントの設定を促される。 アクセスキーとパスワードを生成出来たらcliへ戻る。

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

Successfully set up the new user.

ここでアカウントと初期設定が完了する。

Set up fullstack project

amplifyを用いたReactの初期プロジェクトの構築。

npx create-react-app react-amplified
cd react-amplified

npm startでローカルホストにてReactの初期プロジェクトが立ち上がる。

プロジェクトの初期化。

amplify init

開発環境の設定をする。

Enter a name for the project (react-amplified)

# All AWS services you provision for your app are grouped into an "environment"
# A common naming convention is dev, staging, and production
Enter a name for the environment (dev)

# Sometimes the CLI will prompt you to edit a file, it will use this editor to open those files.
Choose your default editor

# Amplify supports JavaScript (Web & React Native), iOS, and Android apps
Choose the type of app that you're building (javascript)

What JavaScript framework are you using (react)

Source directory path (src)

Distribution directory path (build)

Build command (npm build)

Start command (npm start)

# This is the profile you created with the `amplify configure` command in the introduction step.
Do you want to use an AWS profile

見た目を整える。

npm install aws-amplify @aws-amplify/ui-react
import Amplify from "aws-amplify";
import awsExports from "./aws-exports";
Amplify.configure(awsExports);

Connect API and database to the app

APIの設定を行う。

amplify add api
? Please select from one of the below mentioned services:
# GraphQL
? Provide API name:
# myapi
? 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:
# 7 (or your preferred expiration)
? Do you want to configure advanced settings for the GraphQL API:
# No
? 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
? Do you want to edit the schema now? 
# Yes
type Todo @model {
  id: ID!
  name: String!
  description: String
}

deployする。

amplify push
? Are you sure you want to continue? Y

# You will be walked through the following questions for GraphQL code generation
? Do you want to generate code for your newly created GraphQL API? Y
? Choose the code generation language target: javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Y
? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2

メモの追加と保存したメモの呼び出しを記述する。

/* src/App.js */
import React, { useEffect, useState } from 'react'
import { API, graphqlOperation } from 'aws-amplify'
import { createTodo } from './graphql/mutations'
import { listTodos } from './graphql/queries'

const initialState = { name: '', description: '' }

const App = () => {
  const [formState, setFormState] = useState(initialState)
  const [todos, setTodos] = useState([])

  useEffect(() => {
    fetchTodos()
  }, [])

  function setInput(key, value) {
    setFormState({ ...formState, [key]: value })
  }

  async function fetchTodos() {
    try {
      const todoData = await API.graphql(graphqlOperation(listTodos))
      const todos = todoData.data.listTodos.items
      setTodos(todos)
    } catch (err) { console.log('error fetching todos') }
  }

  async function addTodo() {
    try {
      if (!formState.name || !formState.description) return
      const todo = { ...formState }
      setTodos([...todos, todo])
      setFormState(initialState)
      await API.graphql(graphqlOperation(createTodo, {input: todo}))
    } catch (err) {
      console.log('error creating todo:', err)
    }
  }

  return (
    <div style={styles.container}>
      <h2>Amplify Todos</h2>
      <input
        onChange={event => setInput('name', event.target.value)}
        style={styles.input}
        value={formState.name} 
        placeholder="Name"
      />
      <input
        onChange={event => setInput('description', event.target.value)}
        style={styles.input}
        value={formState.description}
        placeholder="Description"
      />
      <button style={styles.button} onClick={addTodo}>Create Todo</button>
      {
        todos.map((todo, index) => (
          <div key={todo.id ? todo.id : index} style={styles.todo}>
            <p style={styles.todoName}>{todo.name}</p>
            <p style={styles.todoDescription}>{todo.description}</p>
          </div>
        ))
      }
    </div>
  )
}

const styles = {
  container: { width: 400, margin: '0 auto', display: 'flex', flex: 1, flexDirection: 'column', justifyContent: 'center', padding: 20 },
  todo: {  marginBottom: 15 },
  input: { border: 'none', backgroundColor: '#ddd', marginBottom: 10, padding: 8, fontSize: 18 },
  todoName: { fontSize: 20, fontWeight: 'bold' },
  todoDescription: { marginBottom: 0 },
  button: { backgroundColor: 'black', color: 'white', outline: 'none', fontSize: 18, padding: '12px 0px' }
}

export default App

Add authentication

認証を行う。

amplify add auth

? Do you want to use the default authentication and security configuration? Default configuration
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings?  No, I am done.
//src/App.js
import { withAuthenticator } from '@aws-amplify/ui-react'
export default withAuthenticator(App)

Deploy and host app

amplify add hosting

? Select the plugin module to execute: # Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
? Choose a type: # Manual Deployment

amplify publish

一応ここまででチュートリアルは終了する。簡単。

そのほか

あんま用語を分かっていない気がする。 build:コンパイルとリンクを行うこと。

  • コンパイル:機械語へ翻訳する
  • リンク:コンパイルされたファイルを1つの実行ファイルにまとめる deploy:システムを利用可能な状態にすること。システム開発後の設定なども含む。

デプロイにも色々あるんだな。

今さら聞けないデプロイの基本。押さえておきたい用語や定番サービス


More Stories