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

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.

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.

Related

How do I query a particular field in loopback 4 through the repository?

I want to enforce uniqueness so I would like to see if there are any other emails and usernames that are similar to the one posted to this route. How do I do that through the repository, it keeps on asking about a filter which I see but cannot get my head around it.
#post('/users', {
responses: {
'200': {
description: 'User model instance',
content: {'application/json': {schema: {'x-ts-type': User}}},
},
},
})
async create(#requestBody() user: User): Promise<User> {
//check : User= await this.userRepository.create(user);
//#param.query.object('filter', getFilterSchemaFor(User)) filter?: Filter;
// var check:any=await this.userRepository.find(filter);
//filter: Filter;
var check: User = await this.userRepository.find({email:user.email});
var isNotPresent: boolean = true;
// check.forEach(function(val){
// });
// if(isNotPresent)
return await this.userRepository.create(user);
}
A Filter object has the following properties that can be used to define a query and it's response:
where: Used to define a query. In your case, you would like to find existing users with the same email and username as provided in the request body.
fields: To specify fields that you would like to include or exclude in the response of your query. Every object in the array returned by find() will have only those fields which are set to true in the fields object.
offset, skip, limit and order: Used for pagination.
So, in your case, assuming a 'user' has an 'email' and an 'username', the filter object would look like the following:
const filter: Filter = {
where: {
'email': user.email,
'username': user.username
},
fields: {
email: true,
username: true
},
offset: 0,
limit: 10,
skip: 0,
order: [],
};
And your call to the repository method would look like the following:
var check: User = await this.userRepository.find(filter);
My first SO answer. Hope this helps.

Meteor prefill a collection

I have made the following collection in meteor:
CodesData = new Mongo.Collection('CodesData');
CodesDataSchema = new SimpleSchema({
code: {
label: "Code",
type: Number
},
desc: {
label: "Description",
type: String,
}
});
CodesData.attachSchema(CodesDataSchema);
Now I want to prefill this collection with some data.
For example: code: 1 desc: "hello".
How can I do this manually and easily?
You can use Meteor.startup to run some actions on your collection once the server app has been loaded and is starting:
CodesData = new Mongo.Collection('CodesData');
CodesDataSchema = new SimpleSchema({ code: { label: "Code", type: Number }, desc: { label: "Description", type: String, } });
.attachSchema(CodesDataSchema);
Meteor.startup(()=>{
// Only fill if empty, otherwise
// It would fill on each startup
if (CodesData.find().count() === 0) {
CodesData.insert({ code: 1, description: 'some description' });
}
});
If you have a lot of data to prefill you can define it in a JSON and load it on startup:
Consider the following json named as pre:
{
codesdata: [
{ code: 1, description: 'foo' },
{ code: 7, description: 'bar' }
]
}
Meteor.startup(()=>{
const preData = JSON.parse( pre );
preData.codesData.forEach( entry => {
CodesData.insert( entry );
});
});
This allows you to manage your prefill more easily and also let's you version control the json if desired ( and no sensitive data is revealed ).
Considerations:
The function Meteor.startup runs on each start. So you should consider how to avoid unnecessary inserts / prefill that create doubles. A good way is to check if the collection is empty (see first example).
You may put the startup code an another js file in order to separate definitions from startup routines.
The current script does not differentiate between server or client. You should consider to do this on server and create a publication / subscription around it.
More readings:
https://docs.meteor.com/api/core.html#Meteor-startup
Importing a JSON file in Meteor
https://docs.meteor.com/api/core.html#Meteor-settings

How to give configurable URL in tableau WDC

I am trying to build a tabeau WDC.
this is my code
(function () {
var myConnector = tableau.makeConnector();
myConnector.getSchema = function (schemaCallback) {
var cols = [{
id: "month",
dataType: tableau.dataTypeEnum.string
}, {
id: "value1",
alias: "value1",
dataType: tableau.dataTypeEnum.float
}, {
id: "value2",
alias: "value2",
dataType: tableau.dataTypeEnum.float
}];
var tableSchema = {
id: "testfeed",
alias: "test Feed",
columns: cols
};
schemaCallback([tableSchema]);
};
myConnector.getData = function (table, doneCallback) {
$.getJSON('http://test.com/view?name=test&filters=[{"type":"number","id_equals":["123"]}]', function (resp) {
var feat = resp.DATA,
tableData = [];
// Iterate over the JSON object
for (var i = 0, len = feat.length; i < len; i++) {
tableData.push({
"MONTH": feat[I].month,
"ChargeEntryLag_NUMERATOR": feat[i]. value1,
"ChargeEntryLag_DENOMINATOR": feat[i]. value2
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
$(document).ready(function () {
$("#submitButton").click(function () {
tableau.connectionName = "testFeed";
tableau.submit();
});
});
})();
my URL contains some filters as shown in the above code, so if U want to get data for a particular filter I have to hardcode it in URL and the use it.
In other word my URL is static , Is there a way to make it dynamic.
suppose I want the value of 'id' to be 10in my filter, for that I have to go the the WDC code and change it. can it be made configurable.
use tableau.connectionData to pass data. There is an example in this tutorial:
https://tableau.github.io/webdataconnector/docs/wdc_multi_table_tutorial
Typically you'd create a form. When you connect with the WDC in tableau desktop, you put in the URL of your form. The form will store the form vars in tableau.connectData. Your getData can then take those and create a custom Data Source inside tableau desktop for you.
- Mike

Why I can't get document via mongoose?

I'm getting document via MongoDB Shell:
db.page_about_love.find()
But I can't get document via mongoose. What is wrong?
mongoose.connect(db_uri);
var loveSchema = new mongoose.Schema({
title: String,
content: String,
tag: String
});
mongoose.model('page_about_love', loveSchema);
var about = mongoose.model('page_about_love');
about.find(function (err, love) {
if (err) return console.error(err);
console.log(love);
});
Test output:
[]
To prevent Mongoose generating a collection name to use, you should be explicit and pass which collection name it should use:
var loveSchema = new mongoose.Schema({
title: String,
content: String,
tag: String
}, { collection : 'page_about_love' });
Otherwise, Mongoose will apply the utils.toCollectionName() function to the model name to determine the collection name, which in your case would yield page_about_loves (notice the pluralization).
More information here.

Firebase Ionic code implementation

I'm really stuck with this code and can't find the solution. I have created an Ionic app with connection to Firebase and my auth is working fine; can pass the data, but I can't see how should I pass the following code correctly. Form Structure:
My code for passing data, the Service:
factory('Products', function($firebaseArray) {
var productsRef = new Firebase("https://kidsmoments-19623.firebaseio.com/momentos");
var products =$firebaseArray(productsRef.child('products'));
var Products = {
saveProduct: function (product, image) {
var newProduct = {
name: product.name
, tagline: product.tagline
, description: product.description
, price: product.price
, image: image
};
return products.add(newProduct).then(function () { console.log('added');
})
}
};
return Products;
}
)
It looks like you forgot to add 'Products' as a dependency in the controller you were working on.
Also you should try Firebase three-way-binding:
.factory("Products", ["$firebaseObject", "$rootScope",
function($firebaseObject, $rootScope) {
return function() {
// create a reference to the database where our Products is.
var ref = ($rootScope.ref.child("Products"))
return $firebaseObject(reg);
}
}
])
And from the controller:
Products().$bindTo($scope, "products");
Now any change that you do to $scope.products will be synced to Firebase
I believe you have an entity products, so make a reference to that entity and push your data like this:
var productsRef = new Firebase("https://kidsmoments-19623.firebaseio.com/momentos/products");
productsRef.push({
name: product.name,
tagline: product.tagline,
description: product.description,
price: product.price,
image: image
})
Update About the error that you get please make sure you have injected the provider to your settings controller