How to generate queries and mutation string export from schema.graphql

571 views Asked by At

I am building a flutter application and using amplify_flutter 0.2.1 and amplify v5.1.0 , when I pull the project from the Amplify-admin UI it generates a graphQL schema schema.graphql which is useless at front-end because in order to fetch or modify the document, every time we need to write the graphQL query document like this:

String graphQLDocument =
        '''mutation CreateTodo(\$name: String!, \$description: String) {
              createTodo(input: {name: \$name, description: \$description}) {
                id
                name
                description
              }
        }''';

    var operation = Amplify.API.mutate(
        request: GraphQLRequest<String>(document: graphQLDocument, variables: {
      'name': 'my first todo',
      'description': 'todo description',
    }));


Amplify Flutter official CRUD Doc

I want to write it like this:

const input = {
name,
description

};
const output = {
id,name,description
};
var graphQLDoc = createToDO(input,output); // it should return the string object according to the input and output passed.

    var operation = Amplify.API.mutate(
        request: GraphQLRequest<String>(document: graphQLDoc, variables: {
      'name': 'my first todo',
      'description': 'todo description',
    }));

OR it can be advanced like this:

const input = {
name:"hackrx",
description: "this works cool"

};
const output = {
id,name,description
};
var graphQLQueryRes = await createToDO(input,output); // it should return the whole fetched object according to the output passed.

     
1

There are 1 answers

2
Z-Soroush On BEST ANSWER

you can do this way that I use in my code:

String myMutation(name, description) {
var graphQLDocument = '''mutation CreateTodo {
   createTodo(input: {name: $name, description: $description}) {
      id
      name
      description
      }
   }
   ''';
return graphQLDocument;  
}

var operation = Amplify.API.mutate(
      request:
          GraphQLRequest<String>(document: myMutation('john', 'doe')));

for getting the response: you can run amplify codegen models in the terminal that generate data models, based on your schema.graphql tables. and after that, you can do it this way: e.g you have a user table

User.fromJson(operation.response.data['createToDo]);

now you have an object of user class.