How to fetch data from a different firebase project? - javascript

Scenario I have created two projects in firebase using command line tools. The first site(say A) is a web-app that uses hosting, firestore, cloud functions and auth. The second site(say B) is sort of admin-portal which should be able to show all the data in site-A. Site-B uses different Auth than site-A.
Note More sites like site-A will be created in future and site-B will remain the admin-portal of all of them.
Question How to bring the data from one project in firebase to some other project?
PS I know that SO doesn't allow this but if there is a better way of doing this, I would be very happy to know.

You'll have to initialize Firebase multiple times, once for each project. According to the documentation:
// Initialize the default app
firebase.initializeApp(defaultAppConfig);
// Initialize another app with a different config
var otherApp = firebase.initializeApp(otherAppConfig, "other");
console.log(firebase.app().name); // "[DEFAULT]"
console.log(otherApp.name); // "other"
// Use the shorthand notation to retrieve the default app's services
var defaultStorage = firebase.storage();
var defaultDatabase = firebase.database();
// Use the otherApp variable to retrieve the other app's services
var otherStorage = otherApp.storage();
var otherDatabase = otherApp.database();

Related

Is it possible to directly call the AWS SDK from a ServiceNow business rule, and can I use it to update an amazon lex slot?

I have a business rule in SN that translates csv data from a table, turns it into a json object. I need that json object to then be in the format that Amazon Lex requires for slot values. (specific json object structure). With this, I then need to somehow call the aws sdk for authentication reasons, so that i can update the lex bot slot. I have tried the following code, but i know it will not work correctly due to the client-side portion of the script.
(function executeRule(current, previous /*null when async*/) {
var AWS = getTopWindow().document.createElement('script');
AWS.src = 'https://sdk.amazonaws.com/js/aws-sdk-2.388.0.min.js';
g_form.getFormElement().appendChild(AWS);
AWS.onload = function() {
callback();
};
gs.includes('CSVtoJSON');
//this gives access to the object and it's methods / properties
var csvToJSON = new CSVtoJSON();
//this runs the function getAttachmentGR
csvToJSON.getAttachmentGR(sys_id);
})(current, previous);
what could i do here to rectify my issue, if possible?

Firestore: Couldn't Serialize object of type 'ArrayUnionTransform'

I am trying to updates elements in an array using the Firestore docs example:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
var admin = require('firebase-admin');
var washingtonRef = firestore.collection('cities').doc('DC');
var arrUnion = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
However when I do this, I get the following error:
Error: Update() requires either a single JavaScript object or an
alternating list of field/value pairs that can be followed by an
optional precondition. Argument "dataOrField" is not a valid Document.
Couldn't serialize object of type "ArrayUnionTransform" (found in field
regions). Firestore doesn't support JavaScript objects with custom
prototypes (i.e. objects that were created via the "new" operator).
Make sure you are using the correct SDK.
The reason this was not working was because my reference to firestore.collection('cities').doc('DC'); was actually coming from here:
const Firestore = require('#google-cloud/firestore'); // this is the wrong SDK.
const firestore = new Firestore({
projectId: 'my-project'
keyFilename: fbKeyFile
});
As it states on the README.md this is wrong:
Applications that use Google's Server SDKs should not be used in end-user environments, such as on phones or on publicly hosted websites. If you are developing a Web or Node.js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK.
Therefor to get it working I simple switched the following:
firestore.collection('cities').doc('DC');
// to
FirebaseAdmin.firestore().collection('cities').doc('DC');

Javascript: failed in creating a node on Firebase

I am a beginner in Javascript, started learning it 2 days ago because I wanted to set up some cloud functions on Firebase. The database structure of my app (already published) is shown in the figure, and what I want is:
When users upload their "achievements" to Firebase, the cloud function calculates "the total times" that a specific achievement has been achieved by all users. For example, achievements[0] is achieved 80000 times in total, and achievements[28] is achieved 54321 times in total. After calculating them, I store the array under the node "achievementsCount_total", which would be at the same level as the node "users".
To do this, I followed the documents on Firebase and tried to accomplish the cloud function. Here are the codes:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateScores = functions.database.ref('/users/{userUID}/achievements')
.onWrite(event => {
var database=firebase.database();
var achievementsCount_total=new Array();
for(var i=0;i<60;i++){achievementsCount_total[i]=0;}
var allUsersSnapshot = event.data.parent.parent.child('/{userUID}');//a list containing all users
allUsersSnapshot.forEach(function(element) {
var achievements_this = element.child('/achievements').val();
for(var i=0;i<60;i++)
{
achievementsCount_total[i]+=achievements_this[i];
}
}, this);
database.ref('achievementsCount_total').set(achievementsCount_total);
return null;
});
However, the new node("achievementsCount_total") was not created at the same level as "users". I checked it on Firebase and found that the function was successfully executed, while the new node did not show up. Please help me with what I did wrong. Thank u~

Get initial collection values from Firebase

In my node app I try to get access to Firebase, which contains a few collections.
var firebase = require('firebase');
firebase.initializeApp({myConfig: "Here"});
var database = firebase.database();
var rootRef = firebase.database().ref()
How exactly do i get all rows of a particular collection or all collections in database? Printing those variables gives strange structured objects.
You should totally be looking into firebase documentation to get this information.
The way you retrieve will depend on what exact behavior you are expecting. And the documentation is excential to understand how firebase behave as a database in wich one of the possible cases.
var rootRef = firebase.database().ref().on('value', function(snapshot) {
console.log(snapshot.val());
});
Snippet above will look into any change on your entire database (since you are not specifying any child like ref().child("users")) and log it as a javascript Object.
Good luck and, again, go to the documentation. :)

Mongoose how to replace a Model's save() function

I have set up a KeystoneJS project which allows you to get an out-of the box Admin UI for your models.
KeystoneJS works with only one master database, where you define models, and then each Model get its own collection in that master database.
The thing is, I have a separate user database and a separate content database. I am looking to "hijack" the Keystone Models, so that I can plug in the models from my other databases (currently using the mongoose-glue project).
I am 50% there. I got it to read data by replacing the Keystone model's .find() and .findOne() functions like this
var KeystoneUser = new keystone.List('User');
KeystoneUser.add({ /* clone all fields in external model */ });
KeystoneUser.register();
var external = require("mongoose-glue");
var ExternalUser = external.model("ExternalUser")
KeystoneUser.model.find = ExternalUser.find.bind(ExternalUser)
KeystoneUser.model.findOne = ExternalUser.findOne.bind(ExternalUser)
Using the above the Keystone Admin UI works super good for listing and browsing the data in the external database.
But the problem is when it comes to saving.
How can I replace the save function in a similar manner? Also, for some reason when doing the above, all pre/post hooks stop working on both the keystone and the external model..
Solved it with:
KeystoneUser.model.collection = ExternalUser.collection;
That got the hooks to work, so then I just wrote my own save/update hook
KeystoneUser.schema.pre("save", function(next) {
// Trick to remove everything we don't need
var data = JSON.parse(JSON.stringify(this));
if (typeof this.__v === "undefined") {
new ExternalUser(data).save();
} else {
delete data._id;
ExternalUser.findByIdAndUpdate(this._id, data).exec();
}
next();
});

Categories

Resources