AWS Amplifyでローカル環境のモックが使用できるようになりました

2019.08.09

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

ついに、AWS Amplify(以下よりAmpifyと記載)でローカル環境でのモックがサポートされました。
これで開発がちょっと楽になり、テストもしやすくなりますね。

今回のリリースでは下記のリソースのモックが利用可能になりました。

  • AppSync
    • API
    • リゾルバーのテンプレートマッピング
    • DynamoDBがバックエンドの場合
    • Lambda関数
  • Lambda
    • 直接発火する場合
    • AppSyncから呼び出される場合
  • S3
    • ストレージとしてアプリケーションに使用される場合
  • Cognito
    • GraphQLからユーザープール認証をする場合(JWTを実際のサービスから取得する必要有り)

本記事では、こちらのチュートリアルの一部を実際に試してみたいと思います。

前準備

何はともあれAmplify CLIのインストールをします。

$ npm install -g @aws-amplify/cli

プロジェクトの設定を進めていきます。
チュートリアルに従ってReactを使用してアプリケーションを作成していきます。

$ npx create-react-app refillapp
$ cd refillapp

$ amplify init

Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project refillapp
? Enter a name for the environment prd
? Choose your default editor: Vim (via Terminal, Mac OS only)
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react
? Source Directory Path:  src
? Distribution Directory Path: build
? Build Command:  npm run build
? Start Command: npm run 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 PROFILE

✔ 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 <category> add" 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 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

APIの作成

前準備ができたので、APIの準備をサクサクやっていきましょう。
Amplifyはリソースをすぐ作れるのでやっていて気持ちよいですよね。

$ amplify add api

amplify add api
? Please select from one of the below mentioned services GraphQL
? Provide API name: refillapp
? Choose an authorization type for the API API key
? Do you have an annotated GraphQL schema? No
? Do you want a guided schema creation? No
? Provide a custom type name RefillLocation
Creating a base schema for you...

GraphQL schema compiled successfully.

作成が完了したので、GraphQLのスキーマを編集していきます。
プロジェクトディレクトリ直下のamplify/backend/api/refillapp/schema.graphqlにスキーマがあるので編集していきます。

amplify/backend/api/refillapp/schema.graphql

type RefillLocation @model {
  id: ID!
  name: String!
  description: String
  streetAddress: String!
  city: String!
  stateProvinceOrRegion: String
  zipCode: String!
  countryCode: String!
}

モックを使う

普段ならここで、amplify pushして動作を確認したりするのですが、ここでamplify mockをします。
デプロイ前に確認できるのはやはり安心できますよね。

ここで、1つだけ準備が有ります。モックの使用のためにはJavaが必要です。
私はまだインストールしていなかったので、Amazon Correttoをインストールして使用してみました。

$ brew cask install corretto

気を取り直して、モックを動かしてみます。

$ amplify mock

GraphQL schema compiled successfully.

Edit your schema at refillapp/amplify/backend/api/refillapp/schema.graphql or place .graphql files in a directory at refillapp/amplify/backend/api/refillapp/schema
Creating table RefillLocationTable locally
Running GraphQL codegen
? Choose the code generation language target javascript
? 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
✔ Generated GraphQL operations successfully and saved at src/graphql
AppSync Mock endpoint is running at http://xxx.xxx.xxx.xxx:20002

一部マスクしてますが、localhost:20002でモックのエンドポントが動いているようです。
アクセスすると、良くみる画面が現れました。

データを何も追加していないので、一旦ミューテーションで実行してデータを与えます。
左側の+ ADD NEW MUTATIONを押して下記のように入力してから、左上の実行ボタンを押します。

mutatioin MyMutation {
  __typename
  createRefillLocation(input: {
    name: "SkyTree",
    streetAddress: "Tokyo",
    city: "Tokyo",
    zipCode: "111-1111",
    countryCode: "081"
  })
}

レスポンスとして、idが返ってきて実行が成功したことがわかります。

それでは、クエリを投げてみましょう。 左側の+ ADD NEW QUERYを押してクエリを追加します。

query MyQuery {
  __typename
  getRefillLocation(id: "<ENTER ID>") {
    id
    name
    city
  }
}

このクエリを追加したら、実行しましょう。
クエリとミューテーションがあるのでしっかりと選択して実行します。

これは、便利ですね。
localhost:20002はエンドポントでもあるのでもちろんここにクエリを直接投げることも可能です。

最後に

これをみたときに絶対便利だと思って触ってみました。
やはり便利でした。今後の進化がより楽しみです。