リモートで働くプログラマーの検索結果

リモ太がググったことの覚書

NuxtプロジェクトでAmplifyを触ってみる

Amplifyとは

Googleのfirebaseと似たようなもののAWS版という軽い認識で触ってみる

aws.amazon.com

用意されてる機能としては - データストア - 認証 - 分析 - API - AR/VR - インタラクション - 通知 - 予測 - PubSub - ストレージ

Alexaアプリとかも作れるのかな? Webアプリやモバイルのバックエンドとしては必要充分なフルスタックなサーバーレス環境が用意されてる印象

事前準備

  • AWSアカウントを作成
  • CLIをインストール
npm install -g @aws-amplify/cli
amplify configure

ブラウザが立ち上がりAWSへサインイン もう一度立ち上がりAmplify用のIAMの作成を行われaccessKeyIdとsecretAccessKeyの入力を行う

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-FLax7
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&accessKey&userNames=amplify-FLax7&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:  voter

Nuxtプロジェクト準備

Nuxtプロジェクトを新規作成

remoter.hatenablog.com

remoter.hatenablog.com

amplify init

プロジェクトのディレクトリに移動して

amplify init

今回はvoterという名前でプロジェクトを作成

Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project voter
? Enter a name for the environment dev
? 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 vue
? Source Directory Path:  src
? Distribution Directory Path: dist
? Build Command:  npm run-script build
? Start Command: npm run-script 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 voter
Adding backend environment dev to AWS Amplify Console app: d1sn2jeho8usqw
⠙ Initializing project in the cloud...

CREATE_IN_PROGRESS AuthRole                 AWS::IAM::Role             Fri Feb 28 2020 14:05:31 GMT+0900 (日本標準時) Resource creation Initiated
CREATE_IN_PROGRESS UnauthRole               AWS::IAM::Role             Fri Feb 28 2020 14:05:30 GMT+0900 (日本標準時) Resource creation Initiated
CREATE_IN_PROGRESS DeploymentBucket         AWS::S3::Bucket            Fri Feb 28 2020 14:05:30 GMT+0900 (日本標準時)                            
CREATE_IN_PROGRESS AuthRole                 AWS::IAM::Role             Fri Feb 28 2020 14:05:30 GMT+0900 (日本標準時)                            
CREATE_IN_PROGRESS UnauthRole               AWS::IAM::Role             Fri Feb 28 2020 14:05:29 GMT+0900 (日本標準時)                            
CREATE_IN_PROGRESS amplify-voter-dev-140522 AWS::CloudFormation::Stack Fri Feb 28 2020 14:05:26 GMT+0900 (日本標準時) User Initiated             
⠙ Initializing project in the cloud...

CREATE_IN_PROGRESS DeploymentBucket AWS::S3::Bucket Fri Feb 28 2020 14:05:32 GMT+0900 (日本標準時) Resource creation Initiated
⠧ Initializing project in the cloud...

CREATE_COMPLETE AuthRole   AWS::IAM::Role Fri Feb 28 2020 14:05:49 GMT+0900 (日本標準時) 
CREATE_COMPLETE UnauthRole AWS::IAM::Role Fri Feb 28 2020 14:05:48 GMT+0900 (日本標準時) 
⠙ Initializing project in the cloud...

CREATE_COMPLETE amplify-voter-dev-140522 AWS::CloudFormation::Stack Fri Feb 28 2020 14:05:55 GMT+0900 (日本標準時) 
CREATE_COMPLETE DeploymentBucket         AWS::S3::Bucket            Fri Feb 28 2020 14:05:53 GMT+0900 (日本標準時) 
✔ 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

プロジェクト直下に amplifyディレクトリが作成される

amplify add api

amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: voter
? Choose the default authorization type for the API API key
? Enter a description for the API key: voter
? 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: /path/voter/amplify/backend/api/voter/schema.graphql
? Press enter to continue 

The following types do not have '@auth' enabled. Consider using @auth with @model
     - Todo
Learn more about @auth here: https://aws-amplify.github.io/docs/cli-toolchain/graphql#auth 


GraphQL schema compiled successfully.

Edit your schema at /path/voter/amplify/backend/api/voter/schema.graphql or place .graphql files in a directory at /path/voter/amplify/backend/api/voter/schema
Successfully added resource voter 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

今回はほぼデフォルトのまま作成

完了すると amplify/backend/backend-config.jsonapi情報が追記され サンプル用のTODOモデルのshcme情報が amplify/backend/api/voter/schema.graphqlに追加される

{
    "api": {
        "voter": {
            "service": "AppSync",
            "providerPlugin": "awscloudformation",
            "output": {
                "authConfig": {
                    "additionalAuthenticationProviders": [],
                    "defaultAuthentication": {
                        "authenticationType": "API_KEY",
                        "apiKeyConfig": {
                            "description": "voter",
                            "apiKeyExpirationDays": 7
                        }
                    }
                }
            }
        }
    }
}
type Todo @model {
  id: ID!
  name: String!
  description: String
}

amplify hosting add

hosting用のS3を作成

? Select the environment setup: DEV (S3 only with HTTP)
? hosting bucket name voter-20200228143337-hostingbucket
? index doc for the website index.html
? error doc for the website index.html

You can now publish your app using the following command:
Command: amplify publish

実行すると以下の3つのファイルにhostingの情報を書かれる

modified:   amplify/backend/backend-config.json
new file:   amplify/backend/hosting/S3AndCloudFront/parameters.json
new file:   amplify/backend/hosting/S3AndCloudFront/template.json

amplify publish

amplify publish
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name   | Operation | Provider plugin   |
| -------- | --------------- | --------- | ----------------- |
| Api      | voter           | No Change | awscloudformation |
| Hosting  | S3AndCloudFront | No Change | awscloudformation |

No changes detected
npm WARN lifecycle The node binary used for scripts is /.nodenv/shims/node but npm is using /usr/local/Cellar/node/13.2.0/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

> voter@1.0.0 build /path/voter
> nuxt-ts build

ℹ Production build                                                                                                                                            14:43:50
✔ Builder initialized                                                                                                                                         14:43:50
✔ Nuxt files generated                                                                                                                                        14:43:50
ℹ Starting type checking service...                                                                                                           nuxt:typescript 14:43:53
ℹ Using 1 worker with 2048MB memory limit                                                                                                     nuxt:typescript 14:43:53

✔ Client
  Compiled successfully in 28.58s


Hash: 42d78624a2234fb639fd
Version: webpack 4.41.6
Time: 28586ms
Built at: 2020/02/28 14:44:22
                         Asset       Size  Chunks                                Chunk Names
../server/client.manifest.json   13.3 KiB          [emitted]                     
       0299ebfca014d04806ff.js   12.6 KiB       5  [emitted] [immutable]         pages/test
       0327d707d611edfaa9e8.js     10 KiB       2  [emitted] [immutable]         commons.pages/test
       4c2bacbed1d6c49ee0c1.js    396 KiB       7  [emitted] [immutable]  [big]  vendors.app
       527c22050b56621b6a5b.js     37 KiB       0  [emitted] [immutable]         app
       5b9437f0fd606adf55a4.js  817 bytes       4  [emitted] [immutable]         pages/inspire
       9e10a800541fa90ec235.js   22.6 KiB       3  [emitted] [immutable]         pages/index
                      LICENSES  538 bytes          [emitted]                     
       c3a1f163697c69cc62fe.js   2.38 KiB       6  [emitted] [immutable]         runtime
       f74e42ff6cb51d112cee.js    158 KiB       1  [emitted] [immutable]         commons.app
 + 1 hidden asset
Entrypoint app = c3a1f163697c69cc62fe.js f74e42ff6cb51d112cee.js 4c2bacbed1d6c49ee0c1.js 527c22050b56621b6a5b.js

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets: 
  4c2bacbed1d6c49ee0c1.js (396 KiB)
ℹ Generating pages                                                                                                                                            14:44:22
✔ Generated /inspire                                                                                                                                          14:44:22
✔ Generated /test                                                                                                                                             14:44:22
✔ Generated /                                                                                                                                                 14:44:22
frontend build command exited with code 0
✔ Uploaded files successfully.
Your app is published successfully.
http://voter-XXXXX.s3-website-ap-northeast-1.amazonaws.com

最後に表示されたURLにて公開される

次にDatestoreを触るためにamplify用の各種ライブラリをインストール

aws-amplify.github.io

npm i aws-amplify
npm i aws-amplify-vue

plugins/amplify.jsを作成

import Vue from 'vue'
import Amplify, * as AmplifyModules from 'aws-amplify'
import { AmplifyPlugin, components } from 'aws-amplify-vue'
import awsconfig from '@/src/aws-exports'

Amplify.configure(awsconfig)

Vue.use(AmplifyPlugin, AmplifyModules)
Vue.component(components)

nuxt.confg.jsに作成したplugins/amplify.jsを追記

import colors from 'vuetify/es5/util/colors'

export default {
  mode: 'spa',
  // 略
  plugins: [{ src: '~/plugins/amplify.js', ssr: false }], // 追記
  // 略
}
npm install @types/zen-observable
npm install @types/graphql

todo.vueを作成し TODOを追加できるように

<template lang="pug">
  v-container
    v-form.mb-5
      v-text-field(v-model="input.name" label="todo" required)
      v-btn(@click="createTodo") Add
    ul
      li(v-for="(todo, index) in todos" :key='index') {{ todo.name }}
</template>

<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import { API, graphqlOperation } from 'aws-amplify'
import * as mutations from '@/src/graphql/mutations'
import * as queries from '@/src/graphql/queries'

@Component({ components: {} })
class Todo extends Vue {
  input = {
    name: ''
  }

  todos = []

  async created() {
    await this.listTodos()
  }

  async createTodo() {
    if (this.input.name !== '') {
      await API.graphql(
        graphqlOperation(mutations.createTodo, { input: this.input })
      )
      this.input.name = ''
      await this.listTodos()
    } else {
      console.info('input empty')
    }
  }

  async listTodos() {
    const res = await API.graphql(graphqlOperation(queries.listTodos))
    this.todos = res.data.listTodos.items
  }
}
export default Todo
</script>