Amplify Libraries API(GraphQL)/Create, update, delete data

2023/08/06に公開

Using Amplify Graphql client

mutations

  • graphql mutationではcreate update deleteが使える。
  • create
import { API } from "aws-amplify";
import * as mutations from './graphql/mutations';
import { GraphQLQuery } from '@aws-amplify/api';
import { CreateTodoInput, CreateTodoMutation } from './API';

const todoDetails: CreateTodoInput = {
  name: 'Todo 1',
  description: 'Learn AWS AppSync'
};

const newTodo = await API.graphql<GraphQLQuery<CreateTodoMutation>>({ 
  query: mutations.createTodo, 
  variables: { input: todoDetails }
});
  • createAt, updateAtフィールドはappsyncが適当にしてくれるので送る必要なし。
  • graphqloperationをインポートすると、引数オブジェクトを作る際に役立つ。
// ...
import { API, graphqlOperation } from 'aws-amplify';

// equivalent to above example
const newTodo = await API.graphql<GraphQLQuery<CreateTodoMutation>>(
  graphqlOperation(mutations.createTodo, { input: todoDetails })
);
  • update
import { API } from "aws-amplify";
import * as mutations from './graphql/mutations';
import { GraphQLQuery } from '@aws-amplify/api';
import { UpdateTodoInput, UpdateTodoMutation } from './API';

const todoDetails: UpdateTodoInput = {
  id: 'some_id',
  description: 'Updated description'
};

const updatedTodo = await API.graphql<GraphQLQuery<UpdateTodoMutation>>({ 
  query: mutations.updateTodo, 
  variables: { input: todoDetails }
});
  • appsyncスキーマが想定していないフィールドを渡すとエラーで確認できる。
  • delete
import { API } from "aws-amplify";
import * as mutations from './graphql/mutations';
import { GraphQLQuery } from '@aws-amplify/api';
import { DeleteTodoInput, DeleteTodoMutation } from './API';

const todoDetails: DeleteTodoInput = {
  id: 'some_id',
};

const deletedTodo = await API.graphql<GraphQLQuery<DeleteTodoMutation>>({ 
  query: mutations.deleteTodo, 
  variables: { input: todoDetails }
});
  • id渡すだけでいい。
  • 結合済みのテーブル先に消す必要あるのだけ注意

Discussion