SlideShare una empresa de Scribd logo
1 de 28
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Karthik Saligrama, SDE , AWS Mobile
April, 2018
Offline GraphQL apps with AWS AppSync
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
What are we doing today?
• What is GraphQL
• AWS AppSync
• Offline Application Development
• Demo
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Offline/Real-time use cases
Users expect data immediately
• Banking alerts
• News stories
• Multi-player games
• Chat applications
• Shared whiteboards
• AR/VR experiences
• Document collaboration
Users expect data availability offline
• Financial transactions
• News articles
• Games
• Messaging (pending chat)
• Document collaboration
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
What is GraphQL?
• Application Query Language
• Agnostic of underlying Data Store
• != Graph Database
• Optimized for Performance and flexibility
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
How does GraphQL work?
{
"id": "1",
"name": "Get Milk",
“priority": "1"
},
{
"id": “2",
"name": “Go to gym",
“priority": “5"
},…
type Query {
getTodos: [Todo]
}
type Todo {
id: ID!
name: String
description: String
priority: Int
duedate: String
}
query {
getTodos {
id
name
priority
}
}
Model data with
application schema
Client requests what it
needs
Only that data is
returned
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
What are the GraphQL benefits?
• Rapid prototyping and iteration
• Introspection
• Client Performance First
/posts?include=title,author
posts {
title
author
}
REST/RPC GraphQL
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
What are the GraphQL benefits?
• Delegates Power to Clients
/posts
/postsJustTitle
/postsWithTitleAndAuthor
/postsWithTitleAuthorAndContent
/postsWithTitleAuthorContentAndImages
/postsWithTitleAuthorContentImagesAndComments
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
What are the GraphQL benefits?
• Delegates Power to Clients
/graphql
posts {
title
author
}
Posts (maxSize: 10) {
title
authorName
content
}
posts {
title
authorName
content
}
Posts (maxSize: 10) {
title
author {
firstName
lastName
imageUrl
}
content
}
Posts (maxSize: 10) {
title
author {
firstName
lastName
imageUrl(size:80)
}
content
comments{
user
text
}
}
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
What are the GraphQL benefits?
• Include vs Endpoint & Reduction in call Volumes
/posts?include=title,authors
/posts?include=title,authors,authors.firstname, authors.lastname posts {
title
authors {
firstname
lastname
}
}
{
...
“author”:{
“_links”: {
“self”:https://api.example.com/api/author/foo
}
}
...
}
REST/RPC GraphQL
Hypermedia
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
What is AWS AppSync?
AWS AppSync is a managed service for
application data using GraphQL with real-time
capabilities and an offline programming model.
Real-time
Collaboration
Offline Programming
Model with Sync
Flexible Database
Options
Fine-grained
Access Control
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
How does AWS AppSync work?
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
GraphQL data flow in AWS AppSync
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Mocking VTL
{
"arguments": {},
"source": {},
"identity": {
"sub": "uuid",
"issuer": "https://cognito-
idp.{region}.amazonaws.com/{userPoolId}",
"username": "nadia",
"claims": {},
"sourceIp": [
"x.x.x.x"
],
"defaultAuthStrategy": "ALLOW"
}
}
{
"version" : "2018-05-29",
"operation" : "PutItem",
"key" : {
"sub":
$util.dynamodb.toDynamoDBJson($ctx.identity.sub),
},
"attributeValues" :{
"username": { "S" :
"${ctx.identity.username}" },
"lastLoginTime": { "S" :
"$util.time.nowEpochMilliSeconds()" }
}
}
{
"version" : "2018-05-29",
"operation" : "PutItem",
"key" : {
"sub":
$util.dynamodb.toDynamoDBJson($ctx.
identity.sub),
},
"attributeValues" :{
"username": { "S" :
"${context.identity.username}" },
"lastLoginTime": { "S" :
"$util.time.nowEpochMilliSeconds()"
}
}
}
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Debug Resolver Flow
-Amazon CloudWatch logs
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Demo
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Mix/Match datasources on GraphQL fields
searchPosts
addPost
listPosts
type Query {
listPosts: [Post]
searchPosts: [Post]
}
type Mutation {
addPost: Post
}
type Post {
id: ID!
content: String
description: String
ups: Int
downs: Int
}
Amazon ElasticSearch
Amazon DynamoDB
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Offline Application Considerations
• Local Storage (R/W)
• Order of Operations
• Network State Management
• UI Updates
• Conflict Resolution
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS Mobile SDK + AWS AppSync
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS Mobile SDK + AWS AppSync
iOS
let appSyncConfig = try AWSAppSyncClientConfiguration(
url: AppSyncEndpointURL,
serviceRegion: .USWest2,
userPoolsAuthProvider: self,
s3ObjectManager: AWSS3TransferUtility.default())
let appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
Android (Kotlin)
val appsyncClient = AWSAppSyncClient.builder()
.context(this.applicationContext)
.cognitoUserPoolsAuthProvider(this)
.region(Regions.US_WEST_2)
.serverUrl(Constants. APPSYNC_API_URL)
.build()
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS Mobile SDK + AWS AppSync
iOS
let trackSignInMutation = TrackSignInMutation()
self.appSyncClient?.perform(mutation: trackSignInMutation){ (result, error) in
if let error = error as? AWSAppSyncClientError {
print("Error occurred: (error.localizedDescription )")
return
}
...//do more logic
}
Android (Kotlin)
var trackSignIn = TrackSignInMutation()
appsyncClient!!.mutate(signup).enqueue(object : GraphQLCall.Callback<TrackSignInMutation.Data>() {
override fun onFailure(e: ApolloException) {
Log.e(TAG, "Failed signup mutation", e)
}
override fun onResponse(response: Response<SignUpMutation.Data>) {
Log.i(TAG, response.data().toString())
//more business logic
}
})
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Offline mutations
Jane
Version : 2 Updated Document
Jane
Version : 2 Updated Document
Version : 3 Updated Document
Version : 1 New Document
Time
John
John
Jane goes offline
Jane comes back online
Version : 4 Updated Document
John
Jane
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Conflict Resolution and synchronization
Conflict resolution in the cloud
1. Server wins
2. Silent reject
3. Custom logic (AWS Lambda)
- Optimistic version check
- Extend with your own checks
Optional
• Client callback for Conflict Resolution is still
available as a fallback
{
"version" : "2017-02-28",
"operation" : "PutItem",
"key" : {
"id" : { "S" : "1" }
},
"condition" : {
"expression" : "attribute_not_exists(id)"
}
}
Example: Check that an ID doesn’t already exist:
"condition" : {
"expression" : "someExpression"
"conditionalCheckFailedHandler" : {
"strategy" : "Custom",
"lambdaArn" : "arn:..."
}
}
Run Lambda if version wrong:
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Images and rich content
type S3Object {
bucket: String!
key: String!
region: String!
}
input S3ObjectInput {
bucket: String!
key: String!
region: String!
localUri: String!
}
type Profile {
name: String!
profilePic: S3Object!
}
type Mutation {
updatePhoto(name: String!,
profilePicInput: S3ObjectInput!): Profile
}
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
GraphQL Subscriptions
Near Realtime updates of data
Event based mode, triggered by Mutations
- Scalable model, designed as a platform for common use-cases
Can be used with ANY data source in AppSync
- Lambda, DynamoDB, Elasticsearch
mutation addPost( id:123
title:”New post!”
author:”Nadia”){
id
title
author
}
data: [{
id:123,
title:”New Post!”
author:”Nadia”
}]
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
type Subscription {
addedPost: Post
@aws_subscribe(mutations: ["addPost"])
deletedPost: Post
@aws_subscribe(mutations: ["deletePost"])
}
type Mutation {
addPost(id: ID! author: String! title:
String content: String): Post!
deletePost(id: ID!): Post!
}
subscription NewPostSub {
addedPost {
__typename
version
title
content
author
url
}
}
Schema directives
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Demo
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Best practices
• Mutations offline – what UIs actually need to be optimistic?
• Use Subscriptions appropriately
• Large payloads/paginated data: Queries
• Frequent updating deltas: Subscriptions
• Be kind to your customer’s battery & CPU!
• Don’t overcomplicate Conflict Resolution
• Data model appropriately, many app actions simply append to a list
• For custom cases, use a AWS Lambda and keep client logic light (race
conditions)
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
https://aws.amazon.com/appsy
nc/

Más contenido relacionado

Más de Amazon Web Services

Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsAmazon Web Services
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareAmazon Web Services
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSAmazon Web Services
 
API moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAmazon Web Services
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareAmazon Web Services
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWSAmazon Web Services
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckAmazon Web Services
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without serversAmazon Web Services
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...Amazon Web Services
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceAmazon Web Services
 
Come costruire un'architettura Serverless nel Cloud AWS
Come costruire un'architettura Serverless nel Cloud AWSCome costruire un'architettura Serverless nel Cloud AWS
Come costruire un'architettura Serverless nel Cloud AWSAmazon Web Services
 
AWS Serverless per startup: come innovare senza preoccuparsi dei server
AWS Serverless per startup: come innovare senza preoccuparsi dei serverAWS Serverless per startup: come innovare senza preoccuparsi dei server
AWS Serverless per startup: come innovare senza preoccuparsi dei serverAmazon Web Services
 
Crea dashboard interattive con Amazon QuickSight
Crea dashboard interattive con Amazon QuickSightCrea dashboard interattive con Amazon QuickSight
Crea dashboard interattive con Amazon QuickSightAmazon Web Services
 
Costruisci modelli di Machine Learning con Amazon SageMaker Autopilot
Costruisci modelli di Machine Learning con Amazon SageMaker AutopilotCostruisci modelli di Machine Learning con Amazon SageMaker Autopilot
Costruisci modelli di Machine Learning con Amazon SageMaker AutopilotAmazon Web Services
 
Migra le tue file shares in cloud con FSx for Windows
Migra le tue file shares in cloud con FSx for Windows Migra le tue file shares in cloud con FSx for Windows
Migra le tue file shares in cloud con FSx for Windows Amazon Web Services
 
La tua organizzazione è pronta per adottare una strategia di cloud ibrido?
La tua organizzazione è pronta per adottare una strategia di cloud ibrido?La tua organizzazione è pronta per adottare una strategia di cloud ibrido?
La tua organizzazione è pronta per adottare una strategia di cloud ibrido?Amazon Web Services
 
Protect your applications from DDoS/BOT & Advanced Attacks
Protect your applications from DDoS/BOT & Advanced AttacksProtect your applications from DDoS/BOT & Advanced Attacks
Protect your applications from DDoS/BOT & Advanced AttacksAmazon Web Services
 
Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用
Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用
Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用Amazon Web Services
 

Más de Amazon Web Services (20)

Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
 
Computer Vision con AWS
Computer Vision con AWSComputer Vision con AWS
Computer Vision con AWS
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatare
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
 
API moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e web
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
 
Fundraising Essentials
Fundraising EssentialsFundraising Essentials
Fundraising Essentials
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container Service
 
Come costruire un'architettura Serverless nel Cloud AWS
Come costruire un'architettura Serverless nel Cloud AWSCome costruire un'architettura Serverless nel Cloud AWS
Come costruire un'architettura Serverless nel Cloud AWS
 
AWS Serverless per startup: come innovare senza preoccuparsi dei server
AWS Serverless per startup: come innovare senza preoccuparsi dei serverAWS Serverless per startup: come innovare senza preoccuparsi dei server
AWS Serverless per startup: come innovare senza preoccuparsi dei server
 
Crea dashboard interattive con Amazon QuickSight
Crea dashboard interattive con Amazon QuickSightCrea dashboard interattive con Amazon QuickSight
Crea dashboard interattive con Amazon QuickSight
 
Costruisci modelli di Machine Learning con Amazon SageMaker Autopilot
Costruisci modelli di Machine Learning con Amazon SageMaker AutopilotCostruisci modelli di Machine Learning con Amazon SageMaker Autopilot
Costruisci modelli di Machine Learning con Amazon SageMaker Autopilot
 
Migra le tue file shares in cloud con FSx for Windows
Migra le tue file shares in cloud con FSx for Windows Migra le tue file shares in cloud con FSx for Windows
Migra le tue file shares in cloud con FSx for Windows
 
La tua organizzazione è pronta per adottare una strategia di cloud ibrido?
La tua organizzazione è pronta per adottare una strategia di cloud ibrido?La tua organizzazione è pronta per adottare una strategia di cloud ibrido?
La tua organizzazione è pronta per adottare una strategia di cloud ibrido?
 
Protect your applications from DDoS/BOT & Advanced Attacks
Protect your applications from DDoS/BOT & Advanced AttacksProtect your applications from DDoS/BOT & Advanced Attacks
Protect your applications from DDoS/BOT & Advanced Attacks
 
Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用
Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用
Track 6 Session 6_ 透過 AWS AI 服務模擬、部署機器人於產業之應用
 

Offline GraphQL Apps with AWS AppSync - AWS Online Tech Talks

  • 1. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Karthik Saligrama, SDE , AWS Mobile April, 2018 Offline GraphQL apps with AWS AppSync
  • 2. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. What are we doing today? • What is GraphQL • AWS AppSync • Offline Application Development • Demo
  • 3. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Offline/Real-time use cases Users expect data immediately • Banking alerts • News stories • Multi-player games • Chat applications • Shared whiteboards • AR/VR experiences • Document collaboration Users expect data availability offline • Financial transactions • News articles • Games • Messaging (pending chat) • Document collaboration
  • 4. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. What is GraphQL? • Application Query Language • Agnostic of underlying Data Store • != Graph Database • Optimized for Performance and flexibility
  • 5. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. How does GraphQL work? { "id": "1", "name": "Get Milk", “priority": "1" }, { "id": “2", "name": “Go to gym", “priority": “5" },… type Query { getTodos: [Todo] } type Todo { id: ID! name: String description: String priority: Int duedate: String } query { getTodos { id name priority } } Model data with application schema Client requests what it needs Only that data is returned
  • 6. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. What are the GraphQL benefits? • Rapid prototyping and iteration • Introspection • Client Performance First /posts?include=title,author posts { title author } REST/RPC GraphQL
  • 7. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. What are the GraphQL benefits? • Delegates Power to Clients /posts /postsJustTitle /postsWithTitleAndAuthor /postsWithTitleAuthorAndContent /postsWithTitleAuthorContentAndImages /postsWithTitleAuthorContentImagesAndComments
  • 8. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. What are the GraphQL benefits? • Delegates Power to Clients /graphql posts { title author } Posts (maxSize: 10) { title authorName content } posts { title authorName content } Posts (maxSize: 10) { title author { firstName lastName imageUrl } content } Posts (maxSize: 10) { title author { firstName lastName imageUrl(size:80) } content comments{ user text } }
  • 9. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. What are the GraphQL benefits? • Include vs Endpoint & Reduction in call Volumes /posts?include=title,authors /posts?include=title,authors,authors.firstname, authors.lastname posts { title authors { firstname lastname } } { ... “author”:{ “_links”: { “self”:https://api.example.com/api/author/foo } } ... } REST/RPC GraphQL Hypermedia
  • 10. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. What is AWS AppSync? AWS AppSync is a managed service for application data using GraphQL with real-time capabilities and an offline programming model. Real-time Collaboration Offline Programming Model with Sync Flexible Database Options Fine-grained Access Control
  • 11. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. How does AWS AppSync work?
  • 12. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. GraphQL data flow in AWS AppSync
  • 13. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Mocking VTL { "arguments": {}, "source": {}, "identity": { "sub": "uuid", "issuer": "https://cognito- idp.{region}.amazonaws.com/{userPoolId}", "username": "nadia", "claims": {}, "sourceIp": [ "x.x.x.x" ], "defaultAuthStrategy": "ALLOW" } } { "version" : "2018-05-29", "operation" : "PutItem", "key" : { "sub": $util.dynamodb.toDynamoDBJson($ctx.identity.sub), }, "attributeValues" :{ "username": { "S" : "${ctx.identity.username}" }, "lastLoginTime": { "S" : "$util.time.nowEpochMilliSeconds()" } } } { "version" : "2018-05-29", "operation" : "PutItem", "key" : { "sub": $util.dynamodb.toDynamoDBJson($ctx. identity.sub), }, "attributeValues" :{ "username": { "S" : "${context.identity.username}" }, "lastLoginTime": { "S" : "$util.time.nowEpochMilliSeconds()" } } }
  • 14. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Debug Resolver Flow -Amazon CloudWatch logs
  • 15. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Demo
  • 16. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Mix/Match datasources on GraphQL fields searchPosts addPost listPosts type Query { listPosts: [Post] searchPosts: [Post] } type Mutation { addPost: Post } type Post { id: ID! content: String description: String ups: Int downs: Int } Amazon ElasticSearch Amazon DynamoDB
  • 17. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Offline Application Considerations • Local Storage (R/W) • Order of Operations • Network State Management • UI Updates • Conflict Resolution
  • 18. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS Mobile SDK + AWS AppSync
  • 19. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS Mobile SDK + AWS AppSync iOS let appSyncConfig = try AWSAppSyncClientConfiguration( url: AppSyncEndpointURL, serviceRegion: .USWest2, userPoolsAuthProvider: self, s3ObjectManager: AWSS3TransferUtility.default()) let appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig) Android (Kotlin) val appsyncClient = AWSAppSyncClient.builder() .context(this.applicationContext) .cognitoUserPoolsAuthProvider(this) .region(Regions.US_WEST_2) .serverUrl(Constants. APPSYNC_API_URL) .build()
  • 20. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS Mobile SDK + AWS AppSync iOS let trackSignInMutation = TrackSignInMutation() self.appSyncClient?.perform(mutation: trackSignInMutation){ (result, error) in if let error = error as? AWSAppSyncClientError { print("Error occurred: (error.localizedDescription )") return } ...//do more logic } Android (Kotlin) var trackSignIn = TrackSignInMutation() appsyncClient!!.mutate(signup).enqueue(object : GraphQLCall.Callback<TrackSignInMutation.Data>() { override fun onFailure(e: ApolloException) { Log.e(TAG, "Failed signup mutation", e) } override fun onResponse(response: Response<SignUpMutation.Data>) { Log.i(TAG, response.data().toString()) //more business logic } })
  • 21. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Offline mutations Jane Version : 2 Updated Document Jane Version : 2 Updated Document Version : 3 Updated Document Version : 1 New Document Time John John Jane goes offline Jane comes back online Version : 4 Updated Document John Jane
  • 22. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Conflict Resolution and synchronization Conflict resolution in the cloud 1. Server wins 2. Silent reject 3. Custom logic (AWS Lambda) - Optimistic version check - Extend with your own checks Optional • Client callback for Conflict Resolution is still available as a fallback { "version" : "2017-02-28", "operation" : "PutItem", "key" : { "id" : { "S" : "1" } }, "condition" : { "expression" : "attribute_not_exists(id)" } } Example: Check that an ID doesn’t already exist: "condition" : { "expression" : "someExpression" "conditionalCheckFailedHandler" : { "strategy" : "Custom", "lambdaArn" : "arn:..." } } Run Lambda if version wrong:
  • 23. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Images and rich content type S3Object { bucket: String! key: String! region: String! } input S3ObjectInput { bucket: String! key: String! region: String! localUri: String! } type Profile { name: String! profilePic: S3Object! } type Mutation { updatePhoto(name: String!, profilePicInput: S3ObjectInput!): Profile }
  • 24. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. GraphQL Subscriptions Near Realtime updates of data Event based mode, triggered by Mutations - Scalable model, designed as a platform for common use-cases Can be used with ANY data source in AppSync - Lambda, DynamoDB, Elasticsearch mutation addPost( id:123 title:”New post!” author:”Nadia”){ id title author } data: [{ id:123, title:”New Post!” author:”Nadia” }]
  • 25. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. type Subscription { addedPost: Post @aws_subscribe(mutations: ["addPost"]) deletedPost: Post @aws_subscribe(mutations: ["deletePost"]) } type Mutation { addPost(id: ID! author: String! title: String content: String): Post! deletePost(id: ID!): Post! } subscription NewPostSub { addedPost { __typename version title content author url } } Schema directives
  • 26. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Demo
  • 27. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Best practices • Mutations offline – what UIs actually need to be optimistic? • Use Subscriptions appropriately • Large payloads/paginated data: Queries • Frequent updating deltas: Subscriptions • Be kind to your customer’s battery & CPU! • Don’t overcomplicate Conflict Resolution • Data model appropriately, many app actions simply append to a list • For custom cases, use a AWS Lambda and keep client logic light (race conditions)
  • 28. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. https://aws.amazon.com/appsy nc/