Express JS: Send Databse as Variable / Parameter while requiring a module - node.js

Say I have the following code
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const serviceAccount = require("./permissions.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://blah-blah-blah.firebaseio.com"
});
const db = admin.firestore();
app.use("/auth", require("./auth"));
Now the problem is that I have to use the cloud firestore databse functionality, which is curently stored in the variable db, in my auth.js file as well, without using admin.initializeApp a second time. Is there any way to acomplish that, like importing/exporting the db variable etc.
This is where I am using it in auth.js:
const express = require("express");
const auth = express.Router();
db.collection("data")
.doc("sample")
.get()
.then(
document => {
if (document.exists) {
return done(null, {
id: user.id,
name: user.name,
email: user.email
});
} else {
//create document
}
},
err => {
//handle error
}
);
Of course, right now db will be undefined, which is the problem I need to tackle

Since version 1.0.0 of the Firebase SDK for Cloud Functions you have to initialize with admin.initializeApp();, see the doc here.
Then, to interact with Firestore, you just need to use the Admin SDK, for example as follows:
admin.firestore().collection('....').get();
So, if I understand correctly your question, the following changes should do the trick:
index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
//const db = admin.firestore(); not sure you need that here, it depends if you interact (or not) with Firestore in index.js
app.use("/auth", require("./auth"));
auth.js
const admin = require("firebase-admin");
const db = admin.firestore();
//....
db.collection("data")
.doc("sample")
.get()
.then(
document => {
if (document.exists) {
return done(null, {
id: user.id,
name: user.name,
email: user.email
});
} else {
//create document
}
},
err => {
//handle error
}
);
//....

Related

I want to rewrite all documents in a collection with firebase functions

I am developing an app in flutter. I would like to rewrite the value of "life" field of all documents in the "users" collection of the Firestore to "10(int)" at 00:00 Tokyo time.
I managed to write the code anyway, but I am completely clueless about JavaScript and Functions, so it doesn't work.  I would like to know how to correct it. This is my code.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
process.env.TZ = "Asia/Tokyo";
export const checkTimezone = functions.region('asia-northeast1').https.onRequest(async (req, res) => {
console.info(process.env.TZ)
});
exports.timer = functions.pubsub.schedule('00***').onRun((context) => {
functions.logger.info("timer1 start", {structuredData: true});
admin.firestore().collection("users").get().then(function(querySnapshot){
querySnapshot.forEach(function(doc){
doc.ref.update({
life:10
});
});
})
});
The default timezone for Cloud Functions is America/Los_Angeles. You can set the timezone to Asia/Tokyo so the function will run at every midnight in Japan. Also, you must return a promise from the function to terminate it once the updates have been completed. Try refactoring to code as shown below:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.timer = functions.pubsub
.schedule("0 0 * * *")
.timeZone("Asia/Tokyo")
.onRun((context) => {
functions.logger.info("timer1 start", {structuredData: true});
const usersRef = db.collection("users");
return usersRef.get().then((snapshot) => {
const promises = [];
snapshot.forEach((doc, i) => {
promises.push(doc.ref.update({ life: 10 }));
});
return Promise.all(promises);
});
});

Issue with Firebase Cloud function.. not able to read parameters

I am not uunderstanding why this is not working, as it is basic.
Here is my code:
// Init cloud functions
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Used to access entire JSON Nodes as Admin...
admin.initializeApp();
exports.verifyIAP = functions.database.ref('/Users/{userid}/IAP/{groupid}/{rdate}')
.onCreate((snapshot, context) => {
const groupId = context.params.groupid;
console.log('GroupID: ', groupId);
const receiptDate = context.params.rdate;
console.log('receipt Date: ', receiptDate);
const userId = context.params.userid;
console.log('UserID: ', userId);
const receipt = snapshot.val().ReceiptData;
console.log('receipt Data: ', receipt);
});
When the function triggers, the log shows all the variables as undefined!?
What am I missing!?
Your function is working fine. I just tested it and the problem can be pointed on how you insert the data. For testing purposes, Here's a sample code I used to insert data and trigger the function:
// Import Admin SDK
var admin = require("firebase-admin");
var serviceAccount = require("./*******.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://********.firebaseio.com/"
});
var db = admin.database();
var ref = db.ref("Users");
ref.set({
"userId" : {
"IAP" : {
"groupId" : {
"rdate" : {
"ReceiptData" : "testVAl"
}
}
}
}
}).then(result => {
console.log('done')
process.exit(0)
});

I need to index firebase data to algolia , rules in firebase for both read and write requires Authentication (auth!=null)

I am using the code described in the algolia docs. It is working when firebase rules allow both read and write without authentication. This does not work with data which requires authentication. What I can do to add auth in below code ?
I tried using firebase-admin, I think this method will work only when rule is changed to allow read for a single uid.
const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');
const admin = require("firebase-admin");
var serviceAccount = require("./config/serviceAccountKey.json");
// load values from the .env file in this directory into process.env
dotenv.config();
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL
});
firebase.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL
});
admin
.auth()
.createCustomToken('siddharth')
.then((customToken) => {
console.log(customToken);
firebase.auth().authenticateWithCustomToken(customToken);
})
.catch((error) => {
console.log('Error creating custom token:', error);
});
// admin.auth.createCustomToken('siddharth').then(token => {
// });
const database = firebase.database();
const algolia = algoliasearch(
process.env.ALGOLIA_APP_ID,
process.env.ALGOLIA_API_KEY
);
const index = algolia.initIndex(process.env.ALGOLIA_INDEX_NAME);
database.ref('/questions').once('value', questions => {
const records = [];
questions.forEach(question => {
// get the key and data from the snapshot
const childKey = question.key;
const childData = question.val();
// We set the Algolia objectID as the Firebase .key
childData.objectID = childKey;
// Add object for indexing
records.push(childData);
});
console.log(records);
// Add or update new objects
index
.saveObjects(records)
.then(() => {
console.log('questions imported into Algolia');
})
.catch(error => {
console.error('Error when importing question into Algolia', error);
process.exit(1);
});
});
Since this seems to be a Node.js script that accesses Firebase Authentication by using service credentials with the Admin SDK, you can also use that Admin SDK to access the database. Accessing a Firebase service through the Admin SDK with service credentials gives full administrative access, and bypasses any security rules you may have configured for your database.
In code, change:
const database = firebase.database();
To:
const database = admin.database();

Error upon Cloud Function for Firebase deployment

I've been trying to deploy a Cloud Function to my Firebase project.
It's my first time doing so, also my first time programming with JavaScript.
Here's my code in Node.JS:
'use strict'
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
const firebaseTriggers = functions.region('europe-west1').firestore;
const db = admin.firestore();
exports.postNotification = firebaseTriggers
.document('/post notifications/{notificatioId}').onWrite((snap, context) => {
const notifcationRecieverId = snap.data().mReciever;
const payload = {
data: {
notification_type: 'POST',
title: snap.data().mTitle,
body: snap.data().mDescription,
sender_id: snap.data().mSender,
reciever_id: snap.data().mReciever,
notification_id: context.params.notificatioId
}
};
return db.collection('dog owners')
.document(notifcationRecieverId)
.get()
.then(recieverDoc => {
console.log('Retrieving FCM tokens');
const tokens = recieverDoc.data().mTokens;
console.log('Sending notification payload');
return admin.message().sendToDevice(tokens, payload);
});
});
Upong deployment, I'm getting the following error:
Can someone help me understand why?
Firstly you have got space in your colleciton name. This is bad convetion.
post notifications => postNotifications

Getting data from cloud firestore using nodejs takes too long

I am testing firebase with a NodeJs application and when I try to read data from a database that I have created with one collection it gets the data but it takes too much time to log the data on my terminal.
const express = require('express');
const bodyParser = require('body-parser');
const admin = require('firebase-admin');
let serviceAccount = require('./ServiceAccountKey.json');
const app = express();
const port = 3000;
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://database url"
});
let db = admin.firestore();
db.collection('messages').get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
})
.catch((err) => {
console.log('Error getting documents', err);
});
I have also tried to write data on the database but I am always getting the following error when I try to do it using the below code:
let docRef = db.collection('test').doc('alovelace');
let setAda = docRef.set({
first: 'Ada',
last: 'Lovelace',
born: 1815
}).then(function() {
console.log('Data saved!');
}).catch(function(error) {
console.log("Gor an error: ", error);
});
I would like to understand what I am doing wrong since I am reading 1 item only and trying to insert one item only. You support is really appreciated.
There may be some backdated dependencies. Try using
npm update

Resources