How to query objects from a set of key IDs in Firebase? - flutter

Consider the following data structure:
{
"company": {
"idCompany1": {
"data": {
"address": "",
"companyName": "Company 1",
"logo": "assets/Logo1.png",
"nit": "",
"phone": ""
}
},
"idCompany2": {
"data": {
"address": "",
"companyName": "Company 2",
"logo": "assets/Logo2.png",
"nit": "",
"phone": ""
}
},
"idCompany3": {
"data": {
"address": "",
"companyName": "Company 3",
"logo": "assets/Logo3.png",
"nit": "",
"phone": ""
}
}
},
"users": {
"idUser1": {
"data": "user1#test.com",
"companies": {
"idCompany1": true,
"idCompany3": true
}
},
"idUser2": {
"data": "user2#test.com",
"companies": {
"idCompany2": true
}
}
}
}
Basically what I need to do in the case of user1 is to read the data of the companies to which it belongs, this is Company 1 and Company 3. How can I do that?
The way I found, is by obtaining a list of IDs of those companies, which I have in listaIdEmpresas and then consulting each one through a forEach loop in the following way:
Future<List<EmpresaDatosModel>> cargarEmpresaDatosListado(List<String> listaIdEmpresas) async {
final List<EmpresaDatosModel> listaEmpresas = new List();
listaIdEmpresas.forEach((id) async {
Query resp = db.child('company/$id/data');
final snapshot = await resp.once();
final temp = EmpresaDatosModel.fromJson(Map<String,dynamic>.from(snapshot.value));
temp.idEmpresa = id;
listaEmpresas.add(temp);
print('${temp.companyName} up');
await resp.once().then((snapshot) {});
});
listaEmpresas.forEach((element) {print('Emp ${element.companyName}');});
return listaEmpresas;
}
However, this process is not efficient and I need to manage a delay for waiting the loop.
What would be the right way to do query data from a list of Ids directly?

Related

Rules for real time database chat when using an external database

I am trying to secure my real time db. I have the following database structure:
{
"chats": {
"-NMhLlfSU-HYmjmXBzmH": {
"lastMessage": "",
"lastSender": "",
"seen": true,
"timestamp": 1674724449157
},
"members": {
"-NMhLlfSU-HYmjmXBzmH": {
"63cc6d925b51cb7a423393cc": true,
"63d240635b51cb7a423397d5": true
},
},
"users": {
"63cc6d925b51cb7a423393cc": {
"city": "Ituzaingó, Buenos Aires Province, Argentina",
"contacts": {
"63d240635b51cb7a423397d5": true
},
"name": "Joaquin varela",
"picture": "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"
},
"63d240635b51cb7a423397d5": {
"city": "Madrid",
"contacts": {
"63cc6d925b51cb7a423393cc": true
},
"name": "Test Test",
"picture": "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"
},
}
I am trying to implement the rules for it. The only problem is, my auth.uid is not the same as my user_id
Is there any way to secure my database? Maybe passing some user_id argument but I don't know how.
I hope you can help me. Thanks in advance!

Dart - Convert Map of objects fetched via HTTP REST-API

For my Calendar i get the following data as JSON from the Backend (*JAVA-Type = Map<LocalDate, List<Event>>):
{
"2022-05-28": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
}
],
"2022-05-27": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
},
{
"id": 1,
"title": "Testevent",
"fromDate": "2022-05-27T11:21:04.573754",
"toDate": "2022-05-27T12:21:04.573754",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "normal"
}
],
}
My Event Class looks like:
Class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
}
Now i need the same structure i had in the Backend (Map<DateTime, <List<Event>>) for my Calendar widget and i have no real clue on how to do it. I know how to convert json data into an object if i get a list of an object, but how can i store the date as key of the resulting map?
My code by now:
Future<Map<DateTime, List<Event>>> getEvents(DateTime _fromDate, DateTime
_endDate) async {
String _from = _fromDate.toString().split('.').first;
String _end = _endDate.toString().split('.').first;
final response = await get('${_url}calendar/events/$_from/$_end',
headers: {HttpHeaders.authorizationHeader: 'Bearer $_bearer'});
if (response.status.hasError) {
return Future.error('${response.statusText}');
} else {
final parsed = jsonDecode(response.body);
return parsed;
}
}
You need to do something like that:
var json = {...}; // <-- json obj
// method to parse data to map with list Event
dynamic fromJson(Map<String, dynamic> json){
var map = new Map();
json.keys.forEach((key){
// key is the date
map[key] = json[key].map((e) => Event.fromJson(e)).toList(); // <- need to create a method fromJson in your Event class
});
return map;
}
(...)
class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
fromJson(Map<String, dynamic> json) => Event(...); // <- parse json to Event class
}

Flutter Firebase realtime database fetching the wrong node

I have been trying to get a particular field in realtime database. The result is not the one I expected.
Version used Flutter - 3.0.0 firebase_core: ^1.17.0 firebase_database: ^9.0.14
This is the database
{
"patients_today": {
"VN76Y0TNM": {
"MMS07K5CCLT": {
"doctor": "Dr. John M A",
"doctor_id": "MMS07K5CCLT",
"patients": {
"MMXZV5F8A": {
"appointment_end": 1652709621742,
"appointment_start": 1652705121742,
"arrived_at": 1652705098791,
"dob": 712866600000,
"gender": "male",
"id": "MMXZV5F8A",
"mail": "min#min.c",
"mobile": "+919400490000",
"name": "Minhaz MA",
"status": "WAITING"
}
}
}
}
}
}
var ref = await FirebaseDatabase.instanceFor(app:Firebase.app()).ref()
.child("patients_today")
.child("VN76Y0TNM")//clinicId
.child("MMS07K5CCLT")//doctorId
.child("patients")
.child("MMXZV5F8A")//patientId
.get();
var data = ref.value;
The above code is returning the following
{
"MMS07K5CCLT": {
"doctor": "Dr. John M A",
"doctor_id": "MMS07K5CCLT",
"patients": {
"MMXZV5F8A": {
"appointment_end": 1652709621742,
"appointment_start": 1652705121742,
"arrived_at": 1652705098791,
"dob": 712866600000,
"gender": "male",
"id": "MMXZV5F8A",
"mail": "min#min.c",
"mobile": "+919400490000",
"name": "Minhaz MA",
"status": "WAITING"
}
}
}
}
Instead of the following patient object
{
"appointment_end": 1652709621742,
"appointment_start": 1652705121742,
"arrived_at": 1652705098791,
"dob": 712866600000,
"gender": "male",
"id": "MMXZV5F8A",
"mail": "min#min.c",
"mobile": "+919400490000",
"name": "Minhaz MA",
"status": "WAITING"
}
SUMMARY:
Structure - rtdb/"patients_today"/{$clinicId}/{$doctorId}/"patients"/{$patientId}/{patient-data}
Request - rtdb/"patients_today"/{$clinicId}/{$doctorId}/"patients"/{$patientId}
Returning - rtdb/"patients_today"/{$clinicId}
use var ref = await FirebaseDatabase.instance.ref("patients_today/VN76Y0TNM/MMS07K5CCLT/patients/MMXZV5F8A").get();
hope it will help you!

How to filter data and show it in master details view

My Data
link https://api.myjson.com/bins/rwqy
Model
var oModel = new sap.ui.model.json.JSONModel("https://api.myjson.com/bins/rwqy");
sap.ui.getCore().setModel(oModel,'data');
I want to create a SplitApp(Master-Details page). I have created the Master page as a List of User Name from the User dataset. The list should contain the firstname.
var oList = new sap.m.List({
id:"listId",
mode: sap.m.ListMode.SingleSelect,
select: function(){
oController.itemSelected();
}
});
var oItemTemplate = new sap.m.StandardListItem({
id: "sList",title:"{data>firstname}"});
oList.bindAggregation("items","data>/user",oItemTemplate );
return new sap.m.Page({
id:"master",
title: "Claims",
content: [oList]
});
Now in details page I want to show the expenses made by that user(when i select a specific user from master view) in a table.
Now my question is how to filter data and use it for the Details view. Example:
If I select User "X" from Master view list, I should get id 1 from the "user" and Expenseno 1,4 and 7 (as they are associated with uid 1) from "expense", finally i will show the expenses of uid 1 in the details view.
Code I am trying
itemSelected: function(){
var app = sap.ui.getCore().byId("appid");//when a item will b selected first we will get instance of our app
var list = sap.ui.getCore().byId("listId");//then will get instance of the list
var sitem = list.getSelectedItem();
var spath = sitem.oBindingContexts.data.sPath;
var oitem = sap.ui.getCore().getModel('data').getProperty(spath);
console.log(oitem); //oitem has Object { id="", firstname="", lastname=""} values of the selected user.
//***how to get only the id from "oitem" and filter with expense table***//
//var Model = new sap.ui.model.json.JSONModel(oitem); // will use it for details
//sap.ui.getCore().setModel(Model,'item');// view(oitem should contain the filtered data)
app.toDetail("detailsid","show");
},
Please Help, Thank you.
I would suppose you reorganize your data source to something like.
[
{
"id": "1",
"firstname": "x",
"lastname": "k",
"expense": [
{
"expenseno": "1",
"uid": "1",
"item": "c",
"amount": "1500"
},
{
"expenseno": "4",
"uid": "1",
"item": "y",
"amount": "1000"
},
{
"expenseno": "7",
"uid": "1",
"item": "q",
"amount": "900"
}
]
},
{
"id": "2",
"firstname": "y",
"lastname": "kalita",
"expense": [
{
"expenseno": "2",
"uid": "2",
"item": "t",
"amount": "1150"
},
{
"expenseno": "5",
"uid": "2",
"item": "t",
"amount": "3500"
}
]
},
{
"id": "3",
"firstname": "z",
"lastname": "kalita",
"expense": [
{
"expenseno": "6",
"uid": "3",
"item": "s",
"amount": "3500"
},
{
"expenseno": "3",
"uid": "3",
"item": "p",
"amount": "500"
}
]
}
]
You can do this from your initial Data set by something like this
myData.user.forEach(function(d,i){
var exp = myData.expense.filter(function(d1){
if(d1.uid === d.id)return true;
});
console.log(exp);
});
After this it is just relative binding from parent. /Expense will give all the expenses of parent.
Hope this helps.

RestFB parsing many objects into one incorrectly

My restFB code results in writing on one App to my ArrayList. I need the arraylist to fill out properly with the number of appIds return in JSON. Any insights?
Here is my code:
public List<String> fetchAppIdsForUser() {
Connection<FacebookApp> appList = getClient().fetchConnection("me/applications/developer", FacebookApp.class);
List<String> appIds = new ArrayList<String> ();
for (List<FacebookApp> appListTwo : appList) {
for (FacebookApp app : appListTwo) {
appIds.add(app.getAppId());
}
}
return appIds;
}
And here is what is returned in JSON:
{
"data": [
{
"name": "x",
"namespace": "x",
"id": "x"
},
{
"name": "xx",
"namespace": "xx",
"id": "xx"
},
{
"name": "xxx",
"namespace": "xxxx",
"id": "xxxxx"
},
{
"name": "xxxx",
"namespace": "xxxxx",
"id": "xxxxx"
}
],
"paging": {
"next": "https://graph.facebook.com/xxxxx/applications?type=developer&format=json&access_token=XXXXXXXX"
}
}
I solved it using the following:
public List<String> fetchAppIdsForUser() {
Connection<FacebookApp> appList = getClient().fetchConnection("me/applications/developer", FacebookApp.class);
List<FacebookApp> list = appList.getData();
ArrayList<String> appNames = new ArrayList<String>();
for (FacebookApp app: list) {
appNames.add(app.getName());
}
return appNames;
}