dayjournal memo

Total 974 articles!!

Try #035 – AWS AmplifyとVue.jsでデータ登録取得機能を構築してみた

Yasunori Kirimoto's avatar

画像


画像




画像




この記事は、「AWS Amplify Advent Calendar 2019」の21日目の記事です。




AWS AmplifyとVue.jsでデータ登録取得機能を構築してみました!



事前準備


全体の構成はできるだけシンプルに。

バックエンド

  • Amazon Cognito
  • Amazon API Gateway
  • AWS Lambda
  • Amazon DynamoDB

フロントエンド

  • AWS Amplify
  • Vue.js


バックエンド


まずは、バックエンドを構築していきます。

前回、認証機能を追加したので今回はAPI Gateway・Lambda・DynamoDBを組み合わせて、データの登録・取得をするAPI機能を構築します。API構築時にGraphQLも選べますがまたの機会に…


API機能のみであれば2コマンドで実装可能です!

amplify add api

画像

画像

画像

画像


amplify push

画像


処理が完了すると、AWSのコンソールで各サービスが作成されているのを確認できます。


API Gateway 画像

Lambda 画像

DynamoDB 画像


これでバックエンドの構築は完了になります。



フロントエンド


次に、フロントエンドを構築していきます。


実行環境

node v13.1.0
npm v6.13.2


全体構成

画像


package.json

{
  "name": "amplify_prj",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "aws-amplify": "^2.2.0",
    "aws-amplify-vue": "^1.1.1",
    "bootstrap-vue": "^2.0.0-rc.19",
    "core-js": "^2.6.5",
    "vue": "^2.6.10",
    "vue-router": "^3.0.3",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@babel/polyfill": "^7.4.4",
    "@vue/cli-plugin-babel": "^3.8.0",
    "@vue/cli-plugin-eslint": "^3.8.0",
    "@vue/cli-service": "^3.8.0",
    "babel-eslint": "^10.0.1",
    "bootstrap": "^4.3.1",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "mutationobserver-shim": "^0.3.3",
    "node-sass": "^4.12.0",
    "popper.js": "^1.15.0",
    "portal-vue": "^2.1.4",
    "sass-loader": "^7.1.0",
    "vue-cli-plugin-bootstrap-vue": "^0.4.0",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}


src/views


Home.vue

<template>
    <div class='home'>
        <b-container>
            <b-row>
                <b-col sm='12' class='mb-3'>
                    <h3>ログイン済</h3>
                    <hr>
                </b-col>
                <b-col sm='3' class='mx-auto mb-3'>
                    <b-form-input v-model='id' placeholder='id'></b-form-input>
                    <b-form-input v-model='name' placeholder='name'></b-form-input>
                </b-col>
                <b-col sm='12' class='mb-5'>
                    <b-button variant='primary' v-on:click='postData'>登録</b-button>
                </b-col>
                <b-col sm='3' class='mx-auto mb-3'>
                    <b-table striped hover :items='items'></b-table>
                    <b-form-input v-model='text' placeholder='id'></b-form-input>
                </b-col>
                <b-col sm='12' class='mb-5'>
                    <b-button variant='success' v-on:click='getData'>表示</b-button>
                    <hr>
                </b-col>
                <b-col sm='12' class='mb-5'>
                    <!--ログアウトコンポーネント-->
                    <amplify-sign-out></amplify-sign-out>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>

<script>
    // API機能読み込み
    import { API } from 'aws-amplify'

    export default {
        name: 'home',
        components: {
        },
        data() {
            return {
                // API Gatewayの名称
                apiName: 'sampleapigateway',
                // API Gatewayの設定パス
                path: '/sample',
                id: '',
                name: '',
                text: '',
                items: []
            }
        },
        methods: {
            getData: function () {
                // 検索ID指定
                const path = this.path + '/' + this.text;
                // オプション
                const myInit = {
                    headers: {},
                    response: true,
                };
                // データ取得
                API.get(this.apiName, path, myInit).then(response => {
                    // テーブル表示
                    this.items = [
                        {
                            id: response.data[0].id,
                            name: response.data[0].name
                        }
                    ];
                }).catch(error => {
                    // テーブルリセット
                    this.items = [];
                });
            },
            postData: function () {
                // オプション
                const myInit = {
                    headers: {},
                    response: true,
                    body: {
                        id: Number(this.id),
                        name: String(this.name)
                    }
                };
                // データ登録
                API.post(this.apiName, this.path, myInit).then(response => {
                    console.log(response);
                }).catch(error => {
                    console.log(error)
                });
            }
        }
    }
</script>

AmplifyのAPI機能を読み込みます。

// API機能読み込み
import { API } from 'aws-amplify'

データ取得用の関数を設定します。

getData: function () {
    // 検索ID指定
    const path = this.path + '/' + this.text;
    // オプション
    const myInit = {
        headers: {},
        response: true,
    };
    // データ取得
    API.get(this.apiName, path, myInit).then(response => {
        // テーブル表示
        this.items = [
            {
                id: response.data[0].id,
                name: response.data[0].name
            }
        ];
    }).catch(error => {
        // テーブルリセット
        this.items = [];
    });
},

データ登録用の関数を設定します。

postData: function () {
    // オプション
    const myInit = {
        headers: {},
        response: true,
        body: {
            id: Number(this.id),
            name: String(this.name)
        }
    };
    // データ登録
    API.post(this.apiName, this.path, myInit).then(response => {
        console.log(response);
    }).catch(error => {
        console.log(error)
    });
}


簡易ローカルサーバーで確認

npm run serve


ローカルサーバーを立ち上げて、ログインしてみます。

画像


idとnameを入力し登録ボタンを実行します。

画像


AWSのコンソールでDynamoDBを選択し登録できているか確認してみます。

画像


登録したデータのidを指定し表示ボタンを実行します。データが取得され表示確認ができます。

画像




AWS AmplifyとVue.jsでデータ登録取得機能の構築ができました!


AmplifyのAPI追加の記事は、GraphQLの記事が多かったので今回はREST APIの記事を書いてみました。細かい設定はまだまだあったり、Amplifyの使い方を覚える必要はありますが、覚えてしまうと手軽にデータの登録取得機能も構築できるので、Firebaseと同じくサーバーレスアプリケーションを構築する時にとても便利です!



Vue.jsについて、他にも記事を書いています。よろしければぜひ。
tags - Vue.js



book

Q&A