Ionic 1.x + Firebase: add several objects to DB using a loop? - firebase

I'm trying to add to my ionic 1.x app offline capabilities by storing some data to localStorage while offline, and then once online again (networking issues for example) sync the data to the cloud. I came up with this service, however I dont know if this is the correct way to go. Is there a more correct way of pushing several objects to firebase at once\one after another?
.service("syncOFFLINE_Service", function (fireBaseService) {
var dataArray= JSON.parse(localStorage.getItem("offline_data"));
this.syncExpenses = function(){
for(var i = 0; i < dataArray.length; i++){
fireBaseService.addDataToDB(dataArray[i],firebase.auth().currentUser.uid);
}
localStorage.removeItem('offline_expenses');//clear offline data once the loop is over
}
})
And this is the service that adds data (one object at a time) to firebase:
this.addDataToDB = function (expense, uid) {
var newExpenseKey = firebase.database().ref().child('expenses').push().key;
var updates = {};
var keyByDate = "somekey";
updates['/user-expenses/' + uid + '/' + keyByDate + '/'+ newExpenseKey] = expense;
return firebase.database().ref().update(updates);
};

Related

Error: Missing or insufficient permissions when using apps script to get data from Firestore and export it into Google Sheets

I get this exception since I started integrating Google Sheets and Firebase and Firestore. Despite all the tutorials and articles, non of the solutions worked with me.
my issue is when using getDocuments method for retrieving all the docs, the program throws an exception saying Error: Missing or insufficient permissions.
I already project created in Google Cloud, and I have created all the services needed and added all the APIs as instructed from Google Cloud website. Also, I have added oauthscopes needed. unfortunately, it did not work also.
My code:
function getRatingData() {
// Initialize firestore
const firestore = initFirestore();
// Initialize spread sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSpreadSheet = ss.getSheetByName("Sheet1");
// Get all docs
const docs = firestore.getDocuments("rating_debug");
for(var i = 0; i < docs.length; i++){
var array = [];
const lastRow = activeSpreadSheet.getLastRow();
// Get data field of each doc
var date = docs[i].fields["date"];
array.push(date);
var customerID = docs[i].fields["customerID"];
array.push(customerID.stringValue);
var mandoobID = docs[i].fields["mandoobID"];
array.push(mandoobID.stringValue);
var offerUniqueID = docs[i].fields["offerUniqueID"];
array.push(offerUniqueID.stringValue);
var message = docs[i].fields["message"];
array.push(message.stringValue);
var rating = docs[i].fields["rating"];
array.push(rating);
activeSpreadSheet.appendRow(array)[lastRow + 1];
}
}
function initFirestore(){
var config = {
"project_id" : "PROJECT-ID",
"private_key" : "PRIVATE-KEY",
"client_email" : "CLIENT-EMAIL",
};
return FirestoreApp.getFirestore(config.client_email, config.private_key, config.project_id);
}
My oauthScopes
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/script.container.ui",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/datastore",
"https://www.googleapis.com/auth/firebase",
"https://www.googleapis.com/auth/firebase.readonly",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/script.deployments",
"https://www.googleapis.com/auth/script.projects",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/gmail.addons.current.message.metadata",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/script.scriptapp",
"https://www.googleapis.com/auth/script.locale",
"https://www.googleapis.com/auth/documents.currentonly",
"https://www.googleapis.com/auth/spreadsheets.currentonly",
"https://www.googleapis.com/auth/presentations.currentonly",
"https://www.googleapis.com/auth/drive.addons.metadata.readonly",
"https://www.googleapis.com/auth/gmail.addons.current.action.compose",
"https://www.googleapis.com/auth/firebase.database"
This is my output for more clarification
photo of the output

Object overwritten in firebase

Data sending from google sheet:
Script using to send data to firebase from google sheet.
function writeData() {
var ss = SpreadsheetApp.openById("####");
var sheet = ss.getSheets()[0];
var data = sheet.getDataRange().getValues();
var dataToImport = {};
for(var i = 1; i < data.length; i++) {
var department = data[i][0];
var year = data[i][1];
var course = data[i][2];
dataToImport[department] = {};
dataToImport[department][year] = {}
dataToImport[department][year][course] = {}
dataToImport[department][year][course][i] = {
course: data[i][3],
dateAdded: data[i][4],
fileSize: data[i][5],
fileType:data[i][6],
downloadLink: data[i][7],
};
}
var firebaseUrl = "https:url";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
base.setData("",dataToImport);
}
Data that is sent:
Q: My questions that since i had parent electrical and its two childs that were 1 and 2 and each child had a course dsp and aes respectively but only 1 child is send that is the second one.
Why first child is not sent to firebase ?
This code replacing previous entry with new entry. Replace this -
dataToImport[department] = {};
dataToImport[department][year] = {}
dataToImport[department][year][course] = {}
with this -
dataToImport[department] = dataToImport[department] || {};
dataToImport[department][year] = dataToImport[department][year] || {}
dataToImport[department][year][course] = dataToImport[department][year][course] || {}
As a side note to #ra89fi's answer (because I didn't pick up on the overwrite bug).
The line base.setData("",dataToImport); is setting all data at the root of your database ("") with the given data (dataToImport). Any other data in your database will be deleted.
Instead, you should use an update operation.
I unfortunately can't establish which version of the Firebase API you are using. It's not quite the REST API and not quite JavaScript. So here are some relevant documentation links.
REST Update Guide
REST Update Reference
JavaScript (Web) Update Guide
JavaScript (Web) Update Reference

Can't Get Firebase Google App Script Quickstart Tutorial to Work

I can't seem to get the Firebase QuickStart to work for me. I'm pretty sure that I followed all of the instructions correctly. But I'm not getting access to write to the database. And according to the instructions the database is currently open to the public with the suggest rules change displayed below. Has anybody ever gone through this tutorial before? I'd like a hint as to what to do next.
Here's the code.
function writeDataToFirebase() {
var ss = SpreadsheetApp.openById("1rV2_S2q5rcakOuHs2E1iLeKR2floRIozSytAt2iRXo8");
//var ss = SpreadsheetApp.getActive();//I tried running it with data in this spreadsheet copied from the recommended source
var sheet = ss.getSheets()[0];
//var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
var dataToImport = {};
for(var i = 1; i < data.length; i++) {
var firstName = data[i][0];
var lastName = data[i][1];
dataToImport[firstName + '-' + lastName] = {
firstName:firstName,
lastName:lastName,
emailAddress:data[i][2],
country:data[i][4],
department:data[i][5],
weight:data[i][6],
birthDate:data[i][7]
};
}
var firebaseUrl = "https://script-examples.firebaseio.com/";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
base.setData("", dataToImport);
}
The Data:
This is my library dialog:
This is the error I keep on getting:
This name of my script in the FireBase Site:
This is the access rules change:
So I guess I missed an important point. The url of firebase database has your projectId in it. So the url would be something like https://' + projectId + '.firebaseio.com'. Sorry, to bother everyone with such a simple question.

Import cost data from google spreadsheet to google analytics

I am tryig to figure out if i am able to get data from google spreadsheet and import to google analytics. I thought of using API but i am not sure it will work or that's the only way. Anybody know excatly or something on how to sync them together?
Here is a Google Sheet's app script to upload cost data to Google Analytics.
function uploadData() {
var accountId = "xxxxxxxx";
var webPropertyId = "UA-xxxxxxxx-x";
var customDataSourceId = "xxxxxxxx";
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var maxRows = ss.getLastRow();
var maxColumns = ss.getLastColumn();
var data = [];
for (var i = 1; i < maxRows;i++) {
data.push(ss.getRange([i], 1,1, maxColumns).getValues());
}
var newData = data.join("\n");
var blobData = Utilities.newBlob(newData, "application/octet-stream", "GA import data");
try {
var upload = Analytics.Management.Uploads.uploadData(accountId, webPropertyId, customDataSourceId, blobData);
SpreadsheetApp.getUi().alert("Uploading: OK");
}
catch(err) {
SpreadsheetApp.getUi().alert("Cannot upload: Failed");
}
}
Source
You can use the Google Sheets API to extract the data out of your sheet. Then the management API will allow you to upload that data.
The Uploads collection is a set of Upload resources, each of which
describes an upload for one of the user's custom data sources. This
resource should be used when uploading Dimension Widening data.
Try uploads

How to use parallel async in meteor

I am having three functions to fetch screenshots, yelp and google data of a website.The result of these three functions are pushed to an array of subdocuments which will get inserted to database.I need to increase the performance of this api.Is it possible to call these functions using parallel async in meteor without using npm module?
The line of code I used is shown below
Meteor.methods({
insertApart : function(apart){
var google_data = setGoogleData(apart);
var screen_captures_data = setScreenShots(apart);
var yelp_data = setYelpData(apart);
function setGoogleData(apart) {
// code to fetch google data
}
function setScreenShots(apart) {
// code to fetch screen shots
}
function setYelpData(apart) {
// code to fetch yelp data
}
var data=[];
data.google = google_data;// setting google data
data.screen_captures = screen_captures_data;// setting screen captures
data.yelp = yelp_data;// setting yelp data
var id = Apartments.insert(data);
return id;
}
});

Resources