AppSync CRUD

AWS AppSync provides a managed GraphQL API with real-time subscriptions and offline support.

GraphQL Schema

type Job @model @auth(rules: [{ allow: owner }]) {
  id: ID!
  title: String!
  company: String!
  salary: String
  url: String
  owner: String
}

Deploy the API

amplify add api
# Select: GraphQL
# Auth type: Amazon Cognito User Pool

amplify push
# Creates AppSync API + DynamoDB table

CRUD Operations

import { API } from 'aws-amplify'
import { createJob, updateJob, deleteJob } from './graphql/mutations'
import { listJobs, getJob } from './graphql/queries'

// Create
const newJob = await API.graphql({
  query: createJob,
  variables: { input: { title: 'React Native Dev', company: 'NeuroCoder' } }
})

// Read
const jobs = await API.graphql({ query: listJobs })

// Update
await API.graphql({
  query: updateJob,
  variables: { input: { id: 'job-id', title: 'Senior RN Dev' } }
})

// Delete
await API.graphql({
  query: deleteJob,
  variables: { input: { id: 'job-id' } }
})

Real-time Subscriptions

import { onCreateJob } from './graphql/subscriptions'

const subscription = API.graphql({
  query: onCreateJob
}).subscribe({
  next: ({ value }) => {
    console.log('New job:', value.data.onCreateJob)
  }
})

// Unsubscribe when done:
subscription.unsubscribe()