準備
1.amplify add api
コマンドで、GraphQL API を追加する
amplify add api
? Please select from one of the below mentioned services:
> GraphQL
? Here is the GraphQL API that we will create. Select a setting to edit or continue:
> Continue
? Choose a schema template:
> Single object with fields (e.g., “Todo” with ID, name, description)
? Do you want to edit the schema now?
> Yes
2.amplify/backend/api/myapi/schema.graphql
を編集する
type Todo @model {
id: ID!
name: String!
description: String
}
3.amplify push
コマンドで作成した Rest API を AWS にデプロイし、
AWS のAppSync
サービスへ反映する
amplify push
? Are you sure you want to continue? Y
? Do you want to generate code for your newly created GraphQL API? Y
? Choose the code generation language target: javascript (or your preferred language target)
? 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
4.amplify console
コマンドでデプロイしたサービスを確認する
amplify console
実装
import Amplify, { API } from 'aws-amplify';
import config from "./aws-exports";
Amplify.configure(config);
/**
* GraphQL実行
* @param {string} query 作成、更新、削除、検索のGraphQL
* @param {object} input 項目(設定無し可)
* @returns 結果
*/
export async function graphql(query, input = null) {
try {
if (!!input)
return await API.graphql({ query, variables: { input } });
else
return await API.graphql({ query });
} catch (err) {
console.error('error:', err);
}
}
参考
Set up Amplify REST API - JavaScript - AWS Amplify Gen 1 Documentation
Overview - JavaScript - AWS Amplify Gen 1 Documentation
aws-amplify.github.io