Search code examples
graphqlaws-amplifyaws-appsync

AWS Appsync Javascript query example and input syntax


I'm using Amplify and Appsync for a react app I'm building. Right now I'm trying to query a user and am using the appsync client:

const client = new AWSAppSyncClient({
  url: awsconfig.aws_appsync_graphqlEndpoint,
  region: awsconfig.aws_appsync_region,
  auth: {
    type: awsconfig.aws_appsync_authenticationType,
    jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken()
  },
  complexObjectsCredentials: () => Auth.currentCredentials()
});

I've been able to successfully run a mutation using the example provided on the amplify website

const result = await client.mutate({
    mutation: gql(createTodo),
    variables: {
      input: {
        name: 'Use AppSync',
        description: 'Realtime and Offline',
      }
    }
  });

but when it comes to running a query using the client, the only example they provide is with a list operation

const result = await client.query({
    query: gql(listTodos)
  });

They don't provide an example for how to query by a specific ID, so I'm wondering if anybody can shine some light on the syntax for this, provide an example, or point me in the direction of a good reference for this? Thank you in advance.


Solution

  • It's not much different from mutation example, kindly see the code below:

    const getBlog = `query GetBlog($id: ID!) {
      getBlog(id: $id) {
        id
        title
        content
        author
      }
    }
    `;
    


    Run a Query with parameter

       const result = await client.query({
            query: gql(getBlog),
            variables: { id: '0002b432-157a-4b6a-ad67-6a8693e331d1' }
                 });
          console.log(result.data.getBlog);
    


    Or

      const input = { id: '0002b432-157a-4b6a-ad67-6a8693e331d1' }
          const result = await client.query({
                  query: gql(getBlog),
                  variables: input
                                       });
          console.log(result.data.getBlog);