0
0

More than 1 year has passed since last update.

AWS日記35 (Amplify)

Last updated at Posted at 2022-01-31

はじめに

今回は AWS Amplify を試します。
チュートリアルのJavaScriptの手順を参考に、サンプルWebアプリケーションをホスティングします。

初回設定

環境設定

  • 適切なバージョンの Node.js , npm , git をインストールします。
  • 本記事における Node.jsのバージョンは 16.13.2 です。

Amplify CLI インストール

Amplify用のユーザーを追加

  • AdministratorAccess を許可したユーザーを新規に追加します。

プロジェクト作成

ファイル作成

mkdir -p amplify-js-app/src && cd amplify-js-app
touch package.json index.html webpack.config.js src/app.js

パッケージのインストール

npm install

ローカル環境で起動

npm start

バックエンド初期化

amplify init

API作成

API作成

amplify add api

APIデプロイ

amplify push

状態確認

amplify status

src/app.js の最終形

import Amplify, { API, graphqlOperation } from "aws-amplify";

import awsconfig from "./aws-exports";
import { createTodo } from "./graphql/mutations";
import { listTodos } from "./graphql/queries";
import { onCreateTodo } from "./graphql/subscriptions";

Amplify.configure(awsconfig);

async function createNewTodo() {
  const todo = {
    name: "Use AppSync",
    description: `Realtime and Offline (${new Date().toLocaleString()})`,
  };

  return await API.graphql(graphqlOperation(createTodo, { input: todo }));
}

async function getData() {
  API.graphql(graphqlOperation(listTodos)).then((evt) => {
    evt.data.listTodos.items.map((todo, i) => {
      QueryResult.innerHTML += `<p>${todo.name} - ${todo.description}</p>`;
    });
  });
}

const MutationButton = document.getElementById("MutationEventButton");
const MutationResult = document.getElementById("MutationResult");
const QueryResult = document.getElementById("QueryResult");
const SubscriptionResult = document.getElementById("SubscriptionResult");

MutationButton.addEventListener("click", (evt) => {
  createNewTodo().then((evt) => {
    MutationResult.innerHTML += `<p>${evt.data.createTodo.name} - ${evt.data.createTodo.description}</p>`;
  });
});

API.graphql(graphqlOperation(onCreateTodo)).subscribe({
  next: (evt) => {
    const todo = evt.value.data.onCreateTodo;
    SubscriptionResult.innerHTML += `<p>${todo.name} - ${todo.description}</p>`;
  },
});

getData();

Webアプリケーションのホスティング・公開

ホスティング

amplify add hosting

公開

amplify publish

動作確認

103.jpg

終わりに

AWS Amplify を試しました。
コマンドだけでも簡単にアプリケーションを開発できます。
Amplify Studioを利用することでブラウザ上で開発することができる為、今後試そうと思います。

002-2.jpg

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