search
LoginSignup
0

posted at

updated at

AWS Amplify + Vue.jsでサーバレスアプリ開発 vol.2

概要

こちらの記事を参考に、サーバーレスでwebアプリ開発をしたメモシリーズの2つ目です。
https://qiita.com/minato-naka/items/7b445bcf0794189e65a0

vol.1

API(Graphql)でCRUD実装編

vol.1の続きだと③ Authでユーザー登録、ログイン機能実装編になるのですが、今回はAuthは利用せずに作ってみます。
なので今回は④ API(Graphql)でCRUD実装編になります。

AmplifyCLIのaddでバックエンド設定追加

ターミナルでコマンド実行します。
WARNINGが出ます。まぁ…いいでしょう。

>amplify add api
? Select from one of the below mentioned services: (Use arrow keys)
> GraphQL
  REST
? Here is the GraphQL API that we will create. Select a setting to edit or continue (Use arrow keys)
  Name: flowingleaves
  Authorization modes: API key (default, expiration time: 7 days from now)
  Conflict detection (required for DataStore): Disabled
> Continue
? Choose a schema template: (Use arrow keys)
> Single object with fields (e.g., “Todo” with ID, name, description)
  One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
  Blank Schema
⚠️  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY autho
rization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules

✅ GraphQL schema compiled successfully.

Edit your schema at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema.graphql or place .graphql 
files in a directory at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema
? Do you want to edit the schema now? (Y/n) » yes
Edit the file in your editor: C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema.graphql
✅ Successfully added resource flowingleaves 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/api/amplifyvuealbum/schema.graphqlを編集していきます。
書き方は参考記事に記載されているのでそちらをご参照。
ER図?考えてないけどLeafモデル1つで、create DateTimeの項目は自動的に作成されるので、入力されたテキストを保管するmessage項目があればいいでしょう。

/amplify/backend/api/amplifyvuealbum/schema.graphql
# This "input" configures a global authorization rule to enable public access to
# all models in this schema. Learn more about authorization rules here: https://docs.amplify.aws/cli/graphql/authorization-rules
input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY!

type Leaf @model {
  id: ID!
  message: String
}

AmplifyCLIのpushでバックエンドリソース作成

コマンドを実行します。

>amplify push
\ Building resource api/flowingleaves
⚠️  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY autho
rization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules

/ Fetching updates to backend environment: dev from the cloud.✅ GraphQL schema compiled successfully.

Edit your schema at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema.graphql or place .graphql 
files in a directory at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema
√ Successfully pulled backend environment dev from the cloud.
- Building resource api/flowingleaves
⚠️  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY autho
rization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules

✅ GraphQL schema compiled successfully.

Edit your schema at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema.graphql or place .graphql 
files in a directory at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema

    Current Environment: dev

┌──────────┬───────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin   │
├──────────┼───────────────┼───────────┼───────────────────┤
│ Api      │ flowingleaves │ Create    │ awscloudformation │
└──────────┴───────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? (Y/n) Yes

⚠️  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY autho
rization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules

✅ GraphQL schema compiled successfully.

Edit your schema at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema.graphql or place .graphql 
files in a directory at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema
- Building resource api/flowingleaves
⚠️  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY autho
rization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules

✅ GraphQL schema compiled successfully.

Edit your schema at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema.graphql or place .graphql 
files in a directory at C:\Users\yuuki\OneDrive\ドキュメント\開\葉っぱの川流れ\flowing-leaves\amplify\backend\api\flowingleaves\schema
? Do you want to generate code for your newly created GraphQL API (Y/n) Yes
? Choose the code generation language target (Use arrow keys)
> javascript
  typescript
  flow
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 Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2

しばらく待つとCloudFormationやら何やらが動いて各種AWSリソースが作成されます。

UPDATE_COMPLETE amplify-flowingleaves-dev-163656 AWS::CloudFormation::Stack Sun May 22 2022 17:39:02 GMT+0900 (GMT+09:00) 
√ Generated GraphQL operations successfully and saved at src\graphql
√ All resources are updated in the cloud

GraphQL endpoint: https://xxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-api.ap-northeast-1.amazonaws.com/graphql
GraphQL API KEY: xxx-xxxxxxxxxxxxxxxxxxxxxxxxxx

GraphQL transformer version: 2

フロントエンドにバックエンド連携コード実装

今回はデータ登録しかしないアプリなので、
・葉っぱ登録
だけ作ります。

views/leaves/Create.vue
<template>
  <v-container>
    <h1>葉っぱを流す</h1>
    <v-img
      max-height="300"
      max-width="300"
      src='../../../public/img/leaf1.png'
      >
      <v-row align-content="center" style="height: 300px">
        <v-col align="center">{{ form.message }}</v-col>
      </v-row>
    </v-img>
    <v-form
        ref="form"
        v-model="valid"
        lazy-validation
        @submit.prevent="submitCreate">
        <v-text-field
          v-model="form.message"
          :counter="300"
          :rules="nameRules"
          label="思うこと…"
          required
        ></v-text-field>
        <v-btn
          :disabled="!valid"
          color="success"
          class="mr-4"
          type="submit"
        >
          流す
        </v-btn>
      </v-form>
  </v-container>
</template>

<script>
import { API } from 'aws-amplify'
import { createLeaf } from '../../graphql/mutations'

export default {
  name: 'LeafCreate',
  data () {
    return {
      form: {
        message: ''
      },
      valid: true,
      nameRules: [
        v => !!v || 'なにか入力してね',
        v => (v && v.length <= 300) || '300文字未満にしてね'
      ]
    }
  },
  methods: {
    async submitCreate () {
      await API.graphql({
        query: createLeaf,
        variables: { input: this.form }
      })
        .then((result) => {
          console.log(result)
          this.$router.push({ name: 'LeafCreate' })
        })
        .catch((error) => {
          console.log(error)
        })
    }
  }
}
</script>

おわり

次回は⑤ StorageでS3に画像保存実装編は飛ばして、⑥ Hostingでアプリ公開&自動デプロイ実装編です。

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
What you can do with signing up
0