DEVELOPMENT
目次
はじめに
AWS Amplifyを使うと、サーバーサイドの実装が楽になり、ローカルからコマンドを叩いていくだけで、簡単にサーバーサイドの実装ができます。APIから認証、DBまで非常に便利です。今回はたまたまVueのプロジェクトがありましたんで、AmplifyとVue-cliを使って、ログイン認証後、AmplifyでAPIとDBを作成しVueのアプリ上で使用する部分まで実装してみます。 そして、localで試せるように、mockの導入方法と使い方もご紹介します。
実装すること
前提
どういう仕組か
Amplify がCloudformation経由で、必要なものを作成する
バックエンドの構成
実装手順
Amplify のapiを追加
$ amplify add api
? Please select from one of the below mentioned services: (Use arrow keys)
❯ GraphQL
REST
? Provide API name: xxxx-xxxxx API名です
? Choose the default authorization type for the API
API key
❯ Amazon Cognito User Pool <- 今回はCognitoでログイン認証したユーザー向けのAPIなのでコレ
IAM
OpenID Connect
? Do you want to configure advanced settings for the GraphQL API (Use arrow keys)
❯ No, I am done.
Yes, I want to make some additional changes.
? Do you have an annotated GraphQL schema? (y/N) N
? Do you want a guided schema creation? (Y/n) Y
? What best describes your project:
❯ Single object with fields (e.g., “Todo” with ID, name, description) <- シンプルな一つのスキーマで試すならコレ
One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
Objects with fine-grained access control (e.g., a project management app with owner-based authorization)
? Do you want to edit the schema now? No
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 ~/amplify/backend/api/xxxxxxxxx/schema.graphql or place .graphql files in a directory at ~/amplify/backend/api/xxxxxx/schema
Successfully added resource xxxxxxxx locally
これで、必要なファイルが出来ました。
Schemaファイル
- DynamoDB上に作成すべく、もととなるスキーマファイルは
- /amplify/backend/api/xxxxxxxxxxx/schema.graphql となります。
- ToDoアプリとしてシンプルな内容ですが、
type Todo @model {
id: ID!
name: String!
description: String
}
- Todo がテーブル名
- @modelは決まりみたいなもの
- id:IDこれは、idがカラム名: ID が型で、!がrequiredって事になります。必須項目ですね
- 以下のように編集してみます。
- ※作成時にリレーショナルなschemaサンプルの作成も選択できましたが、エラーとなったので、ここで編集することにしました。
type Blog @model @auth(rules: [{allow: owner}]) {
id: ID!
name: String!
posts: [Post] @connection(name: "BlogPosts")
}
type Post @model @auth(rules: [{allow: owner}]) {
id: ID!
title: String!
blog: Blog @connection(name: "BlogPosts")
comments: [Comment] @connection(name: "PostComments")
}
type Comment @model @auth(rules: [{allow: owner}]) {
id: ID!
content: String
post: Post @connection(name: "PostComments")
}
-
Blog、Post、Commentのリレーショナルなテーブル3つ用意します。
Blog > Post > Commentという関係です
-
@authの部分が認証の有無です。詳細はこちらの記事が非常に詳しくまとめています。
- 今回作成時にcognitoの poolIDでの認証を選択しました。
- この一文を入れるだけで、APIへのログイン認証を実装したこととなります、非常に簡単でありがたいです。
Mockでローカルで試す
- install(Mockの実行にJavaが必要ですが、Correttoを入れる)
$ brew cask install corretto
- 実行します
$ amplify mock
GraphQL schema compiled successfully.
Edit your schema at ~/amplify/backend/api/xxxxxxxxx/schema.graphql or place .graphql files in a directory at ~/amplify/backend/api/xxxxxxxxx/schema
Creating table BlogTable locally
Creating table PostTable locally
Creating table CommentTable locally
Running GraphQL codegen
? 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 Y
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
✔ Generated GraphQL operations successfully and saved at src/graphql
AppSync Mock endpoint is running at http://192.168.3.11:20002
- となるので、http://192.168.3.11:20002 にアクセスしてみます。
まずはデータが無いので入れてみます
- 左下のselectボックスをMutationsにして+ボタンを押します
-
Blogデータの登録
- nameにブログの名前入力
-
Postデータの登録
- postBlogIDにBlogデータを登録した際に返ってきたBlogIDを入れる
- titleに任意の名前を入れる
-
Commentデータの登録
- commentPostIDにPostデータを登録した際に返ってきたPostIDを入れる
- contentに任意の文字列を入れる
取得してみる
- Queryにして+
- キャプチャのようにチェックを入れて、Blogの一覧を1件取ってみる
以上このような形で、Mockを使えば、実際pushして(時間かかる)AppSync上に上げてapp上から実行する必要がなく、簡単にGraphQLの内容を確認すること出来ます。
APP から取得してみる
-
Mockを実行した時点で書きにGraphQLのファイルが作成されています。
./src/graphql/queries.js
- このファイルとAmplifyで用意されているmethodを実行してデータを取得します
<template>
<div>
Top
トップページです
<amplify-sign-out></amplify-sign-out>
</div>
</template>
<script>
import { API, graphqlOperation } from "aws-amplify";
import { listBuyHistorys } from '../graphql/queries';
export default {
name: {
"Top"
},
data() {
return {
blogs: []
}
},
async created() {
this.blogs = await API.graphql(graphqlOperation(listBuyHistorys))
console.log('blogs: ', this.blogs)
},
beforeCreate () {
//console.log(this.$router)
}
}
</script>
- createdメソッドで取得してとりあえずconsole logを出力するところまでですね
- 作成や更新は、‘../graphql/mutations’を使用します。
-
同様にこちらを参考に実装します
- またリレーション貼っている場合、どうするか。簡単です。
- 例)todoの下に、todoDetailがある場合
const todoDetails = {
name: 'My todo!',
description: 'Hello world!'
};
const todo = await API.graphql({
query: queries.createTodo,
variables: {input: todoDetails},
});
const deletedTodo = await API.graphql(graphqlOperation(mutations.createTodo, {input: todo}));
- 要するに、todoDetailの内容を、todoのinputに渡せばOKですね
まとめ
ここまで所要時間20分程度でした。こんなに簡単に、しかも認証も出来て最高でした。 是非試してみてください。
参考
株式会社UKAI 代表取締役CEO。建築を専攻していたが、新卒でYahoo!Japanにエンジニアとして入社。その後、転職、脱サラ、フリーランスエンジニアを経て、田舎へ移住し、ゲストハウスの開業、法人成り。ゲストハウス2軒、焼肉店、カフェ、食品製造業を運営しています。詳細はこちらから