How to put a conditional in json post request flutter - flutter

I have this payload that I need to send to a server
"members": [
{
"names": "ben",
"date-of-birth": "1978-01-01",
"gender": "Male",
"surname": "surname",
"role": "Partner",
"total-cut": "100.00"
}
],
Only thing is at times there are no members, and following this am not supposed to send the array at all, it should just be nothing at all, no members.
For clarification, this is an example only, think there is a members object, like the above, schools object, courses object, only at times some of this come up empty and consequently I should omit the empty object entirely.
For example, in the below, if there are no members,,
{
"members": [
{
"names": "ben",
"date-of-birth": "1978-01-01",
"gender": "Male",
"surname": "surname",
"role": "Partner",
"total-cut": "100.00"
}
],
"courses": [
{
"name": "ben",
"number": "32",
"teacher": "Russ",
"cut": "10.00"
}
],
}
how can i create a conditional that omits the members and leaves courses only
{
"courses": [
{
"name": "ben",
"number": "32",
"teacher": "Russ",
"cut": "10.00"
}
],
}
For context this is a post request

I don't know if this has been solved or not yet (I hope yes :P). But this is a practical approach for reference in case others do run into a similar issue.
Problem
Before, here is a problem rephrasing just to make sure we are on the same line. If you have members, add them to the map otherwise no. In both these conditions the map should look like this:
// With members
{
"members": [
{
"names": "member_name",
//...
}
],
"courses": [
{
"name": "course_name",
//...
}
],
}
// Without members
{
"courses": [
{
"name": "course_name",
//...
}
],
}
Solution
In my opinion, the best way to handle this is to declare an empty Map() and conditionally add entries to it as fellows:
Map<String, dynamic> buildMyMap(){
final buffer = <String, dynamic>{};
if(members.isNotEmpty){
// Option 1
buffer.addEntries(MapEntry("members", members));
// Option 2
buffer["members"] = members;
}else{
// (Optional) In case you want to delete pre-existing members
buffer.remove("members");
}
if(courses.isNotEmpty){
// Option 1
buffer.addEntries(MapEntry("courses", courses));
// Option 2
buffer["courses"] = courses;
}else{
// (Optional) in case you want to remove pre-existing courses!
buffer.remove('courses');
}
return buffer;
}

You should declare the parameter members to be optional in your API, then you have no need to send this parameter.

you can do the following
final List members = [];
final List courses = [];
final map = {
if (members.isNotEmpty)
'members': [
for (final member in members)
{
"names": "ben",
"date-of-birth": "1978-01-01",
"gender": "Male",
"surname": "surname",
"role": "Partner",
"total-cut": "100.00"
}
],
if (courses.isNotEmpty)
'courses': [
for (final course in courses)
{
"name": "ben",
"number": "32",
"teacher": "Russ",
"cut": "10.00"
}
]
};
you can use if statement inside a map or a list in flutter,
also, if you want to multiple fields if a condition is met
final map2 = {
if(true)...{
'name': 'name',
'age': '12'
} else ...{
'name': 'NO NAME',
'age': 'NO AGE'
}
};

Related

Flutter: how to groupby of personality

I want groupBy of famousAs of this data.
I got my data from api something like this
Personality:[
0: {
"FullName":"Harry Potter",
"DateOfBirth": "2020/02/16",
"Department":"Branch Operation",
"BirthDay":"Friday"
"famousAs":"Actor"
},
1: {
"FullName":"John Wick",
"DateOfBirth": "2020/02/16",
"Department":"Finance",
"BirthDay":"Friday"
"famousAs":"Actor"
},
2: {
"FullName":"Priyanka Chopara",
"DateOfBirth":2020/02/19,
"Department":"Loan",
"BirthDay":"Monday"
"famousAs":"Actress"
}
]
when i check ,type of this data then it is showing List of dynamic
If your want to group list of data according to their property value.
You can use .where() method to filter out the list.
List filter(List items, String value) =>
items.where((element) => element['famousAs'] == value).toList();
First the api response data from your question is invalid.
If your List is same as following above filter function will work fine.
or if your api response is HashMap change to Map first
[
{
"FullName": "Harry Potter",
"DateOfBirth": "2020/02/16",
"Department": "Branch Operation",
"BirthDay": "Friday",
"famousAs": "Actor"
},
{
"FullName": "John Wick",
"DateOfBirth": "2020/02/16",
"Department": "Finance",
"BirthDay": "Friday",
"famousAs": "Actor"
},
{
"FullName": "Priyanka Chopara",
"DateOfBirth": 2020 / 02 / 19,
"Department": "Loan",
"BirthDay": "Monday",
"famousAs": "Actress"
}
]
Usage..
final actors = filter(items, 'Actor');
final actresses = filter(items, 'Actress');

Mongoose hide fields AFTER populating

Supposed I have this schema
class Room {
member_ids: [String]
owner_ids: [String]
}
And two virtual populates members and owners, which map to User schema (custom path, not _id)
I successfully get the data populated with this:
return this.roomModel
.findOne({ id: roomId })
.select('-_id -__v')
.populate('members owners', '-_id -__v')
.exec();
It now returns
{
"member_ids": [
"1",
"2"
],
"owner_ids": [
"1"
],
"owners": [
{
"id": "1",
"name": "User 1"
}
],
"members": [
{
"id": "1",
"name": "User 1"
},
{
"id": "2",
"name": "User 2"
}
]
}
The thing is, I don't want member_ids and owner_ids to end up in my response. I've tried using select('-member_ids -owner_ids') however the response did not have populated data anymore (I guess the select phase happens before the populate phase?). Is there anyway to achieve this, without resorting to manually removing the fields afterwards? Thank you.

Updating Mongo DB collection field from object to array of objects

I had to change one of the fields of my collection in mongoDB from an object to array of objects containing a lot of data. New documents get inserted without any problem, but when attempted to get old data, it never maps to the original DTO correctly and runs into errors.
subject is the field that was changed in Students collection.
I was wondering is there any way to update all the records so they all have the same data type, without losing any data.
The old version of Student:
{
"_id": "5fb2ae251373a76ae58945df",
"isActive": true,
"details": {
"picture": "http://placehold.it/32x32",
"age": 17,
"eyeColor": "green",
"name": "Vasquez Sparks",
"gender": "male",
"email": "vasquezsparks#orbalix.com",
"phone": "+1 (962) 512-3196",
"address": "619 Emerald Street, Nutrioso, Georgia, 6576"
},
"subject":
{
"id": 0,
"name": "math",
"module": {
"name": "Advanced",
"semester": "second"
}
}
}
This needs to be updated to the new version like this:
{
"_id": "5fb2ae251373a76ae58945df",
"isActive": true,
"details": {
"picture": "http://placehold.it/32x32",
"age": 17,
"eyeColor": "green",
"name": "Vasquez Sparks",
"gender": "male",
"email": "vasquezsparks#orbalix.com",
"phone": "+1 (962) 512-3196",
"address": "619 Emerald Street, Nutrioso, Georgia, 6576"
},
"subject": [
{
"id": 0,
"name": "math",
"module": {
"name": "Advanced",
"semester": "second"
}
},
{
"id": 1,
"name": "history",
"module": {
"name": "Basic",
"semester": "first"
}
},
{
"id": 2,
"name": "English",
"module": {
"name": "Basic",
"semester": "second"
}
}
]
}
I understand there might be a way to rename old collection, create new and insert data based on old one in to new one. I was wondering for some direct way.
The goal is to turn subject into an array of 1 if it is not already an array, otherwise leave it alone. This will do the trick:
update args are (predicate, actions, options).
db.foo.update(
// Match only those docs where subject is an object (i.e. not turned into array):
{$expr: {$eq:[{$type:"$subject"},"object"]}},
// Actions: set subject to be an array containing $subject. You MUST use the pipeline version
// of the update actions to correctly substitute $subject in the expression!
[ {$set: {subject: ["$subject"] }} ],
// Do this for ALL matches, not just first:
{multi:true});
You can run this converter over and over because it will ignore converted docs.
If the goal is to convert and add some new subjects, preserving the first one, then we can set up the additional subjects and concatenate them into one array as follows:
var mmm = [ {id:8, name:"CORN"}, {id:9, name:"DOG"} ];
rc = db.foo.update({$expr: {$eq:[{$type:"$subject"},"object"]}},
[ {$set: {subject: {$concatArrays: [["$subject"], mmm]} }} ],
{multi:true});

How to create Map<String, String> and Map<String, List<String> protobuf scala

I am new to Scala and protobufs. I want to create a object something like this
{
"id": "usr-435-899",
"type": "SALES",
"filters": {
"country": [
"usa",
"germany"
],
"indication": [
"delivery"
]
}
}
So I think I cannot create the POJO like this in protobuf's.
Now I've created different JSON which is
{
"id": "usr-435-899",
"type": "SALES",
"filters": {
"country": {
"value": [
"usa",
"germany"
]
},
"indication": {
"value": [
"delivery"
]
}
}
}
So I've created a proto something like this:
message ListOfValues {
repeated string value = 1;
}
message AuditRequest {
required string id = 1;
required string type = 2;
map<string, ListOfValues> filters = 3;
}
But when I try to hit the api from POSTMAN it says 404 not found
Can anyone tell whats wrong in this? And Can we create proto for first JSON?

Loopback auto relation include filter not working

I have a model called category which can have multiple sub categories and belongs to one category, so, it's a auto related model. So I inserted a few in my database (I am using MongoDB) and I want to retrieve all my categories that doesn't belong to any one and include all it's sub categories, so the url is:
http://localhost:300/api/categories?filter={"where": {"category": {"exists": false}}, "include": [{"categories": ["categories"]}]}
And what should return is this:
[
{
_id: 1,
nome: "Elétrica",
categories: [
{
_id: 2,
nome: "Tomada",
categories: [
{
_id: 3,
nome: "Trocar Tomada"
},
{
_id: 4,
nome: "Tomada em Curto Circuito"
},
{
_id: 5,
nome: "Outros"
}
]
}
]
}
]
But it's returning this:
[
{
"nome": "Elétrica",
"id": "5b7c6e2dcaaa163984a6ee76",
"categorias": []
}
]
And in my model.json, the relation is set like this:
"relations": {
"categories": {
"type": "hasMany",
"model": "category",
"foreignKey": "category"
},
"category": {
"type": "belongsTo",
"model": "category",
"foreignKey": "category"
}
}
One thing to mention, is that if I try the inverse query, so query all my categories which belongs to other category and include that category, it works.
Maybe this isn't a loopback issue or my url it's wrong, maybe the problem is that I actually have to store all the sub categories in the top category on Mongo, but I am not sure about that, so if anyone can help me if this..
I managed to get to work by deleting the belongsTo relation in my model.