Client code generation

You are currently viewing the legacy GraphQL Transformer documentation. View latest documentation

Codegen helps you generate native code for iOS and Android, as well as the generation of types for Flow and TypeScript. It can also generate GraphQL statements (queries, mutations, and subscriptions) so that you don't have to hand code them.

Codegen add workflow triggers automatically when an AppSync API is pushed to the cloud. You will be prompted if you want to configure codegen when an AppSync API is created and if you opt-in for codegen, subsequent pushes prompt you if they want to update the generated code after changes get pushed to the cloud.

When a project is configured to generate code with codegen, it stores all the configuration .graphqlconfig.yml file in the root folder of your project. When generating types, codegen uses GraphQL statements as input. It will generate only the types that are being used in the GraphQL statements.

Statement depth

In the below schema there are connections between Comment -> Post -> Blog -> Post -> Comments. When generating statements codegen has a default limit of 2 for depth traversal. But if you need to go deeper than 2 levels you can change the maxDepth parameter either when setting up your codegen or by passing --maxDepth parameter to codegen

1type Blog @model {
2 id: ID!
3 name: String!
4 posts: [Post] @connection(name: "BlogPosts")
5}
6type Post @model {
7 id: ID!
8 title: String!
9 blog: Blog @connection(name: "BlogPosts")
10 comments: [Comment] @connection(name: "PostComments")
11}
12type Comment @model {
13 id: ID!
14 content: String
15 post: Post @connection(name: "PostComments")
16}
1query GetComment($id: ID!) {
2 getComment(id: $id) {
3 # depth level 1
4 id
5 content
6 post {
7 # depth level 2
8 id
9 title
10 blog {
11 # depth level 3
12 id
13 name
14 posts {
15 # depth level 4
16 items {
17 # depth level 5
18 id
19 title
20 }
21 nextToken
22 }
23 }
24 comments {
25 # depth level 3
26 items {
27 # depth level 4
28 id
29 content
30 post {
31 # depth level 5
32 id
33 title
34 }
35 }
36 nextToken
37 }
38 }
39 }
40}

General Usage

amplify add codegen

1amplify add codegen

The amplify add codegen allows you to add AppSync API created using the AWS console. If you have your API is in a different region then that of your current region, the command asks you to choose the region. If you are adding codegen outside of an initialized amplify project, provide your introspection schema named schema.json in the same directory that you make the add codegen call from. Note: If you use the --apiId flag to add an externally created AppSync API, such as one created in the AWS console, you will not be able to manage this API from the Amplify CLI with commands such as amplify api update when performing schema updates. You cannot add an external AppSync API when outside of an initialized project.

amplify configure codegen

1amplify configure codegen

The amplify configure codegen command allows you to update the codegen configuration after it is added to your project. When outside of an initialized project, you can use this to update your project configuration as well as the codegen configuration.

amplify codegen statements

1amplify codegen statements [--nodownload] [--maxDepth <int>]

The amplify codegen statements command generates GraphQL statements(queries, mutation and subscription) based on your GraphQL schema. This command downloads introspection schema every time it is run, but it can be forced to use previously downloaded introspection schema by passing --nodownload flag.

amplify codegen types

1amplify codegen types

The amplify codegen types [--nodownload] command generates GraphQL types for Flow and typescript and Swift class in an iOS project. This command downloads introspection schema every time it is run, but it can be forced to use previously downloaded introspection schema by passing --nodownload flag.

amplify codegen

1amplify codegen [--maxDepth <int>]

The amplify codegen [--nodownload] generates GraphQL statements and types. This command downloads introspection schema every time it is run but it can be forced to use previously downloaded introspection schema by passing --nodownload flag. If you are running codegen outside of an initialized amplify project, the introspection schema named schema.json must be in the same directory that you run amplify codegen from. This command will not download the introspection schema when outside of an amplify project - it will only use the introspection schema provided.

Workflows

The design of codegen functionality provides mechanisms to run at different points in your app development lifecycle, including when you create or update an API as well as independently when you want to just update the data fetching requirements of your app but leave your API alone. It additionally allows you to work in a team where the schema is updated or managed by another person. Finally, you can also include the codegen in your build process so that it runs automatically (such as from in Xcode).

Flow 1: Create API then automatically generate code

1amplify init
2amplify add api (select GraphQL)
3amplify push

You’ll see questions as before, but now it will also automatically ask you if you want to generate GraphQL statements and do codegen. It will also respect the ./app/src/main directory for Android projects. After the AppSync deployment finishes the Swift file will be automatically generated (Android you’ll need to kick off a Gradle Build step) and you can begin using in your app immediately.

Flow 2: Modify GraphQL schema, push, then automatically generate code

During development, you might wish to update your GraphQL schema and generated code as part of an iterative dev/test cycle. Modify & save your schema in amplify/backend/api/<apiname>/schema.graphql then run:

1amplify push

Each time you will be prompted to update the code in your API and also ask you if you want to run codegen again as well, including regeneration of the GraphQL statements from the new schema.

Flow 3: No API changes, just update GraphQL statements & generate code

One of the benefits of GraphQL is the client can define it's data fetching requirements independently of the API. Amplify codegen supports this by allowing you to modify the selection set (e.g. add/remove fields inside the curly braces) for the GraphQL statements and running type generation again. This gives you fine-grained control over the network requests that your application is making. Modify your GraphQL statements (default in the ./graphql folder unless you changed it) then save the files and run:

1amplify codegen types

A new updated Swift file will be created (or run Gradle Build on Android for the same). You can then use the updates in your application code.

Flow 4: Shared schema, modified elsewhere (e.g. console or team workflows)

Suppose you are working in a team and the schema is updated either from the AWS AppSync console or on another system. Your types are now out of date because your GraphQL statement was generated off an outdated schema. The easiest way to resolve this is to regenerate your GraphQL statements, update them if necessary, and then generate your types again. Modify the schema in the console or on a separate system, then run:

1amplify codegen statements
2amplify codegen types

You should have newly generated GraphQL statements and Swift code that matches the schema updates. If you ran the second command your types will be updated as well. Alternatively, if you run amplify codegen alone it will perform both of these actions.

Flow 5: Introspection Schema outside of an initialized project

If you would like to generate statements and types without initializing an amplify project, you can do so by providing your introspection schema named schema.json in your project directory and adding codegen from the same directory. To download your introspection schema from an AppSync api, in the AppSync console go to the schema editor and under "Export schema" choose schema.json.

1amplify add codegen

Once codegen has been added you can update your introspection schema, then generate statements and types again without re-entering your project information.

1amplify codegen

You can update your project and codegen configuration if required.

1amplify configure codegen
2amplify codegen

iOS usage

This section will walk through the steps needed to take an iOS project written in Swift and add Amplify to it along with a GraphQL API using AWS AppSync. If you are a first time user, we recommend starting with a new Xcode project and a single View Controller.

Setup

After completing the Amplify Getting Started navigate in your terminal to an Xcode project directory and run the following:

1amplify init ## Select iOS as your platform
2amplify add api ## Select GraphQL, API key, "Single object with fields Todo application"
3amplify push ## Sets up backend and prompts you for codegen, accept the defaults

The add api flow above will ask you some questions, like if you already have an annotated GraphQL schema. If this is your first time using the CLI select No and let it guide you through the default project "Single object with fields (e.g., “Todo” with ID, name, description)" as it will be used in the code generation examples below. Later on, you can always change it.

Since you added an API the amplify push process will automatically prompt you to enter the codegen process and walk through the configuration options. Accept the defaults and it will create a file named API.swift in your root directory (unless you choose to name it differently) as well as a directory called graphql with your documents. You also will have an awsconfiguration.json file that the AppSync client will use for initialization.

Next, modify your Podfile with a dependency of the AWS AppSync SDK:

1target 'PostsApp' do
2 use_frameworks!
3 pod 'AWSAppSync'
4end

Run pod install from your terminal and open up the *.xcworkspace Xcode project. Add the API.swift and awsconfiguration.json files to your project (File->Add Files to ..->Add) and then build your project ensuring there are no issues.

Initialize the AppSync client

Inside your application delegate is the best place to initialize the AppSync client. The AWSAppSyncServiceConfig represents the configuration information present in awsconfiguration.json file. By default, the information under the Default section will be used. You will need to create an AWSAppSyncClientConfiguration and AWSAppSyncClient like below:

1import AWSAppSync
2
3@UIApplicationMain
4class AppDelegate: UIResponder, UIApplicationDelegate {
5
6 var appSyncClient: AWSAppSyncClient?
7
8 func application(
9 _ application: UIApplication,
10 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
11 ) -> Bool {
12
13 do {
14 // You can choose your database location if you wish, or use the default
15 let cacheConfiguration = try AWSAppSyncCacheConfiguration()
16
17 // AppSync configuration & client initialization
18 let appSyncConfig = try AWSAppSyncClientConfiguration(
19 appSyncServiceConfig: AWSAppSyncServiceConfig(),
20 cacheConfiguration: cacheConfiguration
21 )
22 appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
23 } catch {
24 print("Error initializing appsync client. \(error)")
25 }
26 // other methods
27 return true
28 }

Next, in your application code where you wish to use the AppSync client, such in a Todos class which is bound to your View Controller, you need to reference this in the viewDidLoad() lifecycle method:

1import AWSAppSync
2
3class Todos: UIViewController{
4 //Reference AppSync client
5 var appSyncClient: AWSAppSyncClient?
6
7 override func viewDidLoad() {
8 super.viewDidLoad()
9 //Reference AppSync client from App Delegate
10 let appDelegate = UIApplication.shared.delegate as! AppDelegate
11 appSyncClient = appDelegate.appSyncClient
12 }
13}

Queries

Now that the backend is configured, you can run a GraphQL query. The syntax is appSyncClient?.fetch(query: <NAME>Query() {(result, error)}) where <NAME> comes from the GraphQL statements that amplify codegen types created. For example, if you have a ListTodos query your code will look like the following:

1//Run a query
2appSyncClient?.fetch(query: ListTodosQuery()) { (result, error) in
3 if error != nil {
4 print(error?.localizedDescription ?? "")
5 return
6 }
7 result?.data?.listTodos?.items!.forEach { print(($0?.name)! + " " + ($0?.description)!) }
8}

Optionally, you can set a cache policy on the query like so:

1appSyncClient?.fetch(query: ListTodosQuery(), cachePolicy: .returnCacheDataAndFetch) { (result, error) in

returnCacheDataAndFetch will pull results from the local cache first before retrieving data over the network. This gives a snappy UX as well as offline support.

Mutations

For adding data now you will need to run a GraphQL mutation. The syntax appSyncClient?.perform(mutation: <NAME>Mutation() {(result, error)}) where <NAME> comes from the GraphQL statements that amplify codegen types created. However, most GraphQL schemas organize mutations with an input type for maintainability, which is what the Amplify CLI does as well. Therefore you'll pass this as a parameter called input as in the example below:

1let mutationInput = CreateTodoInput(name: "Use AppSync", description:"Realtime and Offline")
2
3appSyncClient?.perform(
4 mutation: CreateTodoMutation(input: mutationInput)
5) { (result, error) in
6 if let error = error as? AWSAppSyncClientError {
7 print("Error occurred: \(error.localizedDescription )")
8 }
9 if let resultError = result?.errors {
10 print("Error saving the item on server: \(resultError)")
11 return
12 }
13}

Subscriptions

Finally it's time to setup a subscription to realtime data. The syntax appSyncClient?.subscribe(subscription: <NAME>Subscription() {(result, transaction, error)}) where <NAME> comes from the GraphQL statements that amplify codegen types created.

1// Subscription notifications will only be delivered as long as this is retained
2var subscriptionWatcher: Cancellable?
3
4//In your app code
5do {
6 subscriptionWatcher = try appSyncClient?.subscribe(
7 subscription: OnCreateTodoSubscription(),
8 resultHandler: { (result, transaction, error) in
9 if let result = result {
10 print(result.data!.onCreateTodo!.name + " " + result.data!.onCreateTodo!.description!)
11 } else if let error = error {
12 print(error.localizedDescription)
13 }
14 }
15 )
16} catch {
17 print("Error starting subscription.")
18}

Subscriptions can also take input types like mutations, in which case they will be subscribing to particular events based on the input. Learn more about Subscription arguments in AppSync here.

Complete Sample

AppDelegate.swift

1import UIKit
2import AWSAppSync
3
4@UIApplicationMain
5class AppDelegate: UIResponder, UIApplicationDelegate {
6
7 var window: UIWindow?
8 var appSyncClient: AWSAppSyncClient?
9
10 func application(
11 _ application: UIApplication,
12 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
13 ) -> Bool {
14 do {
15 // You can choose your database location if you wish, or use the default
16 let cacheConfiguration = try AWSAppSyncCacheConfiguration()
17
18 // AppSync configuration & client initialization
19 let appSyncConfig = try AWSAppSyncClientConfiguration(appSyncServiceConfig: AWSAppSyncServiceConfig(), cacheConfiguration: cacheConfiguration)
20 appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
21 } catch {
22 print("Error initializing appsync client. \(error)")
23 }
24 return true
25 }
26}

ViewController.swift

1import UIKit
2import AWSAppSync
3
4class ViewController: UIViewController {
5
6 var appSyncClient: AWSAppSyncClient?
7
8 // Subscription notifications will only be delivered as long as this is retained
9 var subscriptionWatcher: Cancellable?
10
11 override func viewDidLoad() {
12 super.viewDidLoad()
13 let appDelegate = UIApplication.shared.delegate as! AppDelegate
14 appSyncClient = appDelegate.appSyncClient
15
16 // Note: each of these are asynchronous calls. Attempting to query the results of `runMutation` immediately
17 // after calling it probably won't work--instead, invoke the query in the mutation's result handler
18 runMutation()
19 runQuery()
20 subscribe()
21 }
22
23 func subscribe() {
24 do {
25 subscriptionWatcher = try appSyncClient?.subscribe(subscription: OnCreateTodoSubscription()) {
26 // The subscription watcher's result block retains a strong reference to the result handler block.
27 // Make sure to capture `self` weakly if you use it
28 // [weak self]
29 (result, transaction, error) in
30 if let result = result {
31 print(result.data!.onCreateTodo!.name + " " + result.data!.onCreateTodo!.description!)
32 // Update the UI, as in:
33 // self?.doSomethingInTheUIWithSubscriptionResults(result)
34 // By default, `subscribe` will invoke its subscription callbacks on the main queue, so there
35 // is no need to dispatch to the main queue.
36 } else if let error = error {
37 print(error.localizedDescription)
38 }
39 }
40 } catch {
41 print("Error starting subscription.")
42 }
43 }
44
45 func runMutation(){
46 let mutationInput = CreateTodoInput(name: "Use AppSync", description:"Realtime and Offline")
47 appSyncClient?.perform(mutation: CreateTodoMutation(input: mutationInput)) { (result, error) in
48 if let error = error as? AWSAppSyncClientError {
49 print("Error occurred: \(error.localizedDescription )")
50 }
51 if let resultError = result?.errors {
52 print("Error saving the item on server: \(resultError)")
53 return
54 }
55 // The server and the local cache are now updated with the results of the mutation
56 }
57 }
58
59 func runQuery(){
60 appSyncClient?.fetch(query: ListTodosQuery()) {(result, error) in
61 if error != nil {
62 print(error?.localizedDescription ?? "")
63 return
64 }
65 result?.data?.listTodos?.items!.forEach { print(($0?.name)! + " " + ($0?.description)!) }
66 }
67 }
68}

Android usage

This section will walk through the steps needed to take an Android Studio project written in Java and add Amplify to it along with a GraphQL API using AWS AppSync. If you are a first time user, we recommend starting with a new Android Studio project and a single Activity class.

Setup

After completing the Amplify Getting Started navigate in your terminal to an Android Studio project directory and run the following:

1amplify init ## Select iOS as your platform
2amplify add api ## Select GraphQL, API key, "Single object with fields Todo application"
3amplify push ## Sets up backend and prompts you for codegen, accept the defaults

The add api flow above will ask you some questions, like if you already have an annotated GraphQL schema. If this is your first time using the CLI select No and let it guide you through the default project "Single object with fields (e.g., “Todo” with ID, name, description)" as it will be used in the code generation examples below. Later on, you can always change it.

Since you added an API the amplify push process will automatically enter the codegen process and prompt you for configuration. Accept the defaults and it will create a file named awsconfiguration.json in the ./app/src/main/res/raw directory that the AppSync client will use for initialization. To finish off the build process there are Gradle and permission updates needed.

First, in the project's build.gradle, add the following dependency in the build script:

1classpath 'com.amazonaws:aws-android-sdk-appsync-gradle-plugin:2.6.+'

Next, in the app's build.gradle add in a plugin of apply plugin: 'com.amazonaws.appsync' and a dependency of implementation 'com.amazonaws:aws-android-sdk-appsync:2.6.+'. For example:

1apply plugin: 'com.android.application'
2apply plugin: 'com.amazonaws.appsync'
3android {
4 // Typical items
5}
6dependencies {
7 // Typical dependencies
8 implementation 'com.amazonaws:aws-android-sdk-appsync:2.6.+'
9 implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
10 implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
11}

Finally, update your AndroidManifest.xml with updates to <uses-permissions>for network calls and offline state. Also add a <service> entry under <application> for MqttService for subscriptions:

1<uses-permission android:name="android.permission.INTERNET"/>
2<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3<uses-permission android:name="android.permission.WAKE_LOCK" />
4<uses-permission android:name="android.permission.READ_PHONE_STATE" />
5<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
6<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
7
8 <!--other code-->
9
10 <application
11 android:allowBackup="true"
12 android:icon="@mipmap/ic_launcher"
13 android:label="@string/app_name"
14 android:roundIcon="@mipmap/ic_launcher_round"
15 android:supportsRtl="true"
16 android:theme="@style/AppTheme">
17
18 <service android:name="org.eclipse.paho.android.service.MqttService" />
19
20 <!--other code-->
21 </application>

Build your project ensuring there are no issues.

Initialize the AppSync client

Inside your application code, such as the onCreate() lifecycle method of your activity class, you can initialize the AppSync client using an instance of AWSConfiguration() in the AWSAppSyncClient builder. This reads configuration information present in the awsconfiguration.json file. By default, the information under the Default section will be used.

1private AWSAppSyncClient mAWSAppSyncClient;
2
3 @Override
4 protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.activity_main);
7 mAWSAppSyncClient = AWSAppSyncClient.builder()
8 .context(getApplicationContext())
9 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
10 .build();
11 }

Queries

Now that the backend is configured, you can run a GraphQL query. The syntax of the callback is GraphQLCall.Callback<{NAME>Query.Data> where {NAME} comes from the GraphQL statements that amplify codegen types created. You will invoke this from an instance of the AppSync client with a similar syntax of .query(<NAME>Query.builder().build()). For example, if you have a ListTodos query your code will look like the following:

1public void query(){
2 mAWSAppSyncClient.query(ListTodosQuery.builder().build())
3 .responseFetcher(AppSyncResponseFetchers.CACHE_AND_NETWORK)
4 .enqueue(todosCallback);
5 }
6
7 private GraphQLCall.Callback<ListTodosQuery.Data> todosCallback = new GraphQLCall.Callback<ListTodosQuery.Data>() {
8 @Override
9 public void onResponse(@Nonnull Response<ListTodosQuery.Data> response) {
10 Log.i("Results", response.data().listTodos().items().toString());
11 }
12
13 @Override
14 public void onFailure(@Nonnull ApolloException e) {
15 Log.e("ERROR", e.toString());
16 }
17 };

You can optionally change the cache policy on AppSyncResponseFetchers but we recommend leaving CACHE_AND_NETWORK as it will pull results from the local cache first before retrieving data over the network. This gives a snappy UX as well as offline support.

Mutations

For adding data now you will need to run a GraphQL mutation. The syntax of the callback is GraphQLCall.Callback<{NAME}Mutation.Data> where {NAME} comes from the GraphQL statements that amplify codegen types created. However, most GraphQL schemas organize mutations with an input type for maintainability, which is what the Amplify CLI does as well. Therefore you'll pass this as a parameter called input created with a second builder. You will invoke this from an instance of the AppSync client with a similar syntax of .mutate({NAME}Mutation.builder().input({Name}Input).build()) like so:

1public void mutation(){
2 CreateTodoInput createTodoInput = CreateTodoInput.builder().
3 name("Use AppSync").
4 description("Realtime and Offline").
5 build();
6
7 mAWSAppSyncClient.mutate(CreateTodoMutation.builder().input(createTodoInput).build())
8 .enqueue(mutationCallback);
9}
10
11private GraphQLCall.Callback<CreateTodoMutation.Data> mutationCallback = new GraphQLCall.Callback<CreateTodoMutation.Data>() {
12 @Override
13 public void onResponse(@Nonnull Response<CreateTodoMutation.Data> response) {
14 Log.i("Results", "Added Todo");
15 }
16
17 @Override
18 public void onFailure(@Nonnull ApolloException e) {
19 Log.e("Error", e.toString());
20 }
21};

Subscriptions

Finally, it's time to set up a subscription to real-time data. The callback is just AppSyncSubscriptionCall.Callback and you invoke it with a client .subscribe() call and pass in a builder with the syntax of {NAME}Subscription.builder() where {NAME} comes from the GraphQL statements that amplify codegen types created. Note that the Amplify GraphQL transformer has a common nomenclature of putting the word On in front of a subscription like the below example:

1private AppSyncSubscriptionCall subscriptionWatcher;
2
3 private void subscribe(){
4 OnCreateTodoSubscription subscription = OnCreateTodoSubscription.builder().build();
5 subscriptionWatcher = mAWSAppSyncClient.subscribe(subscription);
6 subscriptionWatcher.execute(subCallback);
7 }
8
9 private AppSyncSubscriptionCall.Callback subCallback = new AppSyncSubscriptionCall.Callback() {
10 @Override
11 public void onResponse(@Nonnull Response response) {
12 Log.i("Response", response.data().toString());
13 }
14
15 @Override
16 public void onFailure(@Nonnull ApolloException e) {
17 Log.e("Error", e.toString());
18 }
19
20 @Override
21 public void onCompleted() {
22 Log.i("Completed", "Subscription completed");
23 }
24 };

Subscriptions can also take input types like mutations, in which case they will be subscribing to particular events based on the input. Learn more about Subscription arguments in AppSync here.

Sample

MainActivity.java

1import android.util.Log;
2import com.amazonaws.mobile.config.AWSConfiguration;
3import com.amazonaws.mobileconnectors.appsync.AWSAppSyncClient;
4import com.amazonaws.mobileconnectors.appsync.AppSyncSubscriptionCall;
5import com.amazonaws.mobileconnectors.appsync.fetcher.AppSyncResponseFetchers;
6import com.apollographql.apollo.GraphQLCall;
7import com.apollographql.apollo.api.Response;
8import com.apollographql.apollo.exception.ApolloException;
9import javax.annotation.Nonnull;
10import amazonaws.demo.todo.CreateTodoMutation;
11import amazonaws.demo.todo.ListTodosQuery;
12import amazonaws.demo.todo.OnCreateTodoSubscription;
13import amazonaws.demo.todo.type.CreateTodoInput;
14
15public class MainActivity extends AppCompatActivity {
16
17 private AWSAppSyncClient mAWSAppSyncClient;
18 private AppSyncSubscriptionCall subscriptionWatcher;
19
20 @Override
21 protected void onCreate(Bundle savedInstanceState) {
22 super.onCreate(savedInstanceState);
23 setContentView(R.layout.activity_main);
24 mAWSAppSyncClient = AWSAppSyncClient.builder()
25 .context(getApplicationContext())
26 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
27 .build();
28 query();
29 mutation();
30 subscribe();
31 }
32
33 private void subscribe(){
34 OnCreateTodoSubscription subscription = OnCreateTodoSubscription.builder().build();
35 subscriptionWatcher = mAWSAppSyncClient.subscribe(subscription);
36 subscriptionWatcher.execute(subCallback);
37 }
38
39 private AppSyncSubscriptionCall.Callback subCallback = new AppSyncSubscriptionCall.Callback() {
40 @Override
41 public void onResponse(@Nonnull Response response) {
42 Log.i("Response", response.data().toString());
43 }
44
45 @Override
46 public void onFailure(@Nonnull ApolloException e) {
47 Log.e("Error", e.toString());
48 }
49
50 @Override
51 public void onCompleted() {
52 Log.i("Completed", "Subscription completed");
53 }
54 };
55
56 public void query(){
57 mAWSAppSyncClient.query(ListTodosQuery.builder().build())
58 .responseFetcher(AppSyncResponseFetchers.CACHE_AND_NETWORK)
59 .enqueue(todosCallback);
60 }
61
62 private GraphQLCall.Callback<ListTodosQuery.Data> todosCallback = new GraphQLCall.Callback<ListTodosQuery.Data>() {
63 @Override
64 public void onResponse(@Nonnull Response<ListTodosQuery.Data> response) {
65 Log.i("Results", response.data().listTodos().items().toString());
66 }
67
68 @Override
69 public void onFailure(@Nonnull ApolloException e) {
70 Log.e("ERROR", e.toString());
71 }
72 };
73
74 public void mutation(){
75
76 CreateTodoInput createTodoInput = CreateTodoInput.builder().
77 name("Use AppSync").
78 description("Realtime and Offline").
79 build();
80
81 mAWSAppSyncClient.mutate(CreateTodoMutation.builder().input(createTodoInput).build())
82 .enqueue(mutationCallback);
83
84 }
85
86 private GraphQLCall.Callback<CreateTodoMutation.Data> mutationCallback = new GraphQLCall.Callback<CreateTodoMutation.Data>() {
87 @Override
88 public void onResponse(@Nonnull Response<CreateTodoMutation.Data> response) {
89 Log.i("Results", "Added Todo");
90 }
91
92 @Override
93 public void onFailure(@Nonnull ApolloException e) {
94 Log.e("Error", e.toString());
95 }
96 };
97}