Transaction failure while testing firebase firestore - javascript

I am trying to write some tests for the cloud functions I have written, but I am facing a problem where a transaction never succeeds and ends up in an error:
9 FAILED_PRECONDITION: the stored version (1648901730789554) does not match the required base version (0)
Problematic code is the following:
await firebase.db().runTransaction((t) => {
return t.get(docRef).then((doc) => {
if (!doc.exists) {
console.log("no exist");
}
});
});
It is run several times (checked with debugger), and then the error messages is thrown...
And the firebase test env init:
export async function initialize() {
fb.initializeTestApp({
projectId: "my-test-project",
auth: { uid: "alice", email: "alice#example.com" }
});
const testEnv = await initializeTestEnvironment({
projectId: "demo-project-1234",
firestore: {
rules: fs.readFileSync("../firestore.rules", "utf8"), // Load rules from file
// host and port can be omitted if they can be discovered from the hub.
},
});
const alice = testEnv.authenticatedContext(uid);
const db = (alice.firestore() as unknown) as firestore.Firestore;
firebase.db = () => db;
return testEnv;
}
Am I doing something wrong?
Note: I currently have only one test that runs, nothing else. And firebase emulators are running, without any other app accessing it.

After some more research, I have figured out that I was mixing #firebase/testing and firebase-admin, and the matter should not be used for unit testing backend functions according to this post.
On a side note, it seems there already is a function to create a doc iff it does not exist:
docRef.create(...).then(() => log("ok")).catch(() => log("Not ok"))

Related

Error when testing against Firebase Emulator 'Expected type 'Pa', but it was: a custom Fa object'

I'm currently attempting to execute the following test in Cypress.
before(async () => {
testEnv = await initializeTestEnvironment({
projectId: MY_PROJECT_ID,
firestore: {
host: "localhost",
port: 8080,
},
});
});
describe("Authorized user can write to collection", () => {
it("Can write to firestore doc", async () => {
console.log("testEnv", testEnv);
const alice = testEnv.authenticatedContext("alice", { role: "user" });
console.log("alice", alice);
const firestore = alice.firestore();
console.log("firestore", firestore);
const testA = await assertSucceeds(
setDoc(alice.firestore(), "/users/alice"),
{
foo: "bar",
}
);
console.log("testA", testA);
});
});
The test fails before the final console.log during the setDoc call. The error is
Expected type 'Pa', but it was: a custom Fa object
I believe I traced this custom Fa object to the _delegate property on the firestore variable, but I am unclear of how to proceed from here.
I make sure that the emulators are all running before running npx cypress open
I tried setting the firestore property via the hub and get the same result
I have also tried passing a 'rules' property to firestore as a string
Any help would be greatly appreciated!

verifyIdToken method doesn't exist in Auth type using getAuth from firebase/auth

I'm trying to follow the example given here where it shows the following example to verify an ID token:
// idToken comes from the client app
getAuth()
.verifyIdToken(idToken)
.then((decodedToken) => {
const uid = decodedToken.uid;
// ...
})
.catch((error) => {
// Handle error
});
My code looks like this:
function createFirebaseAdminApp(config: AppOptions) {
if (getApps().length === 0) {
return initializeApp(config);
} else {
return getApp();
}
}
const options: AppOptions = {
credential: cert({
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey:
process.env.FIREBASE_PRIVATE_KEY != undefined
? process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n")
: "",
}),
databaseURL: process.env.FIREBASE_DATABASE_URL,
};
const firebaseAdmin = createFirebaseAdminApp(options) as FirebaseApp;
const adminAuth = getAuth(firebaseAdmin);
adminAuth
.verifyIdToken(token)
.then((decodedToken) => {
res.locals.decodedToken = decodedToken;
next();
})
.catch(() => {
next(new HttpError("Invalid token provided", 403));
});
But I keep getting
Property 'verifyIdToken' does not exist on type 'Auth'
I have the latest version of the firebase package, which I assume the example given by the docs is using considering it uses getAuth, so can't tell what I'm doing wrong. Also I'm trying to avoid mixing firebase-admin and firebase, not sure if this is correct, but if I mixed them I can't seem to avoid having to initialize too App instances.
Thanks for any help!
You are mixing up the Admin SDK and the client SDK.
The documentation you linked is for the Admin SDK only. Notice how it is organized in the section for Admin. It is not using getAuth anywhere in that page. The Admin SDK is initialized completely differently than the client SDK, and it does not work at all in browsers. It runs on secure backens only.
The client SDK that you're using doesn't have a function for verifying tokens. That is for secure backends only using the Adminn SDK.

Firebase Realtime database showing strange behavior

I am using react-native-firebase in an ejected expo app and trying to build a presence detection system in my chat app which will detect that if the message recipient is online and if not when was he/she was last online. The data will be stored as follows in firebase realtime database:
{
lastSeen:[{
[userId]:{
state: boolean
time: serverTimeStamp
}
}]
}
The problem is that firebase console never shows the data and only if recipient is online then app shows this data (even though its not visible in console) but if user is offline then nothing is returned and no error generated. I have set read and write to true in realtimeDB rules. Here is the code I am using:
import database from "#react-native-firebase/database";
export const updateUserLastSeen = (userId) => {
const userStatusDatabaseRef = database().ref("/lastSeen/" + userId);
console.log("updatelast", userId);
userStatusDatabaseRef
.set({
state: true,
time: database.ServerValue.TIMESTAMP,
})
.then(() => console.log("online"))
.catch((e) => console.log(e));
// database()
// .ref(".info/connected")
// .on("value", function (snapshot) {
// if (snapshot.val() == false) {
// return;
// }
userStatusDatabaseRef
.onDisconnect()
.set({
state: false,
time: database.ServerValue.TIMESTAMP,
})
.then(function () {
console.log("disconnect configured");
// userStatusDatabaseRef.set({
// state: true,
// time: database.ServerValue.TIMESTAMP,
// });
});
// });
};
export const checkUserLastSeen = (userId, setUserLastSeen) => {
console.log("check last", userId);
database()
.ref("/lastSeen/" + userId)
.on("value", (snapshot) => {
setUserLastSeen(snapshot.val());
console.log("User data: ", snapshot.val());
});
console.log("after check last");
};
I tried both the code from firebase docs and rnfirebase docs. In above code, none of the "then" or "catch" functions get called in updateUserLastSeen but in checkUserLastSeen "on" is invoked only if bearer of userId is online. Also, I am using realtime db only for this purpose and cloud firestore for other data storing and its working fine.
Any help would be appreciated. Thanks.
If neither then nor catch of a write is called, it typically means that the client is not connected to the server.
I recommend checking to make sure your app has a network connection, and that you've configured the (correct) URL for your database.

Google Firebase authentication in ReactNative App

I was developing an app which I like implements Firebase as Authenticating system.
My problem comes when I try to set up the Authentication with Google provider when I try to modify the colletion of firestore where the users are saved. My code is the following:
export const loginWithGoogle = () => {
const navigation = useNavigation();
useEffect(() => {
setTimeout(() => {
navigation.navigate('/RegisterScreen');
}, 10000);
}, []);
return () => {
return firebase
.auth()
.signInWithPopup(Providers.google)
.then(async result => {
//console.log(result.credential.accessToken);
const user = result.user;
console.log(user);
//This 2 lines below doesn't work to get the colletion.
db.('users').setItem('userid', user!.uid);
collection.(db,'users').setItem('photoURL', user!.photoURL);
//TODO if userid exists IN USERS db then use update IF NULL use set
await db.collection('users').doc(user!.uid).update({
// id: user.uid,
name: user!.displayName,
email: user!.email,
phone: user!.phoneNumber,
photoURL: user!.photoURL,
});
})
.then(() => {
navigation.navigate('ProtectedScreen');
})
.catch(err => {
console.log(err);
});
};
};
So I guess that my error comes from unknowledge of how to manage data saved on firestore.
If you can help take thanks in advance !
There are some thing we need to clear here:
You can just merge the data. There is no need to read/get it from Firestore to check if it is there and save it onyl if it's not. You will be charged for reads and writes. In the end it's cheaper to always just write without checking if something exists.
Also this code here:
db.('users').setItem('userid', user!.uid);
collection.(db,'users').setItem('photoURL', user!.photoURL);
especially with the db.( and collection.( doens't look good. Even if it is it's not for getting data but for saving it.
Could you pls clarify witch Firebase SDK you use: version 8 or 9. Also pls check a little bit the docs here.

How to fix firebase database initialised multiple times due to React SSR initialised database and cloud function firebase initialised database?

I have updated the question as found the root cause of the issue.
As I have hosted my React SSR app which uses firebase database in the client serving by one of the cloud function named app throwing an error of Error: FIREBASE FATAL ERROR: Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.. When I comment out one by one and deploy, works perfectly. But when I deploy together doesn't work. How do I separate these two keeping both at the same repo?
ORIGINAL Question: Why firebase cloud function throwing an error of 'The default Firebase app does not exist.'?
So I am trying out firebase function for the first time. admin.messaging() throwing me the following error. Help me figure out why?
If I look at the console I get results till console.log('deviceToken', deviceToken);
so whats wrong in const messageDone = await admin.messaging().sendToDevice(deviceToken, payload);?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.updateUnreadCount = functions.database.ref('/chats/{chatId}/{messageId}')
.onCreate(async(snap, context) => {
const appOptions = JSON.parse(process.env.FIREBASE_CONFIG);
appOptions.databaseAuthVariableOverride = context.auth;
const adminApp = admin.initializeApp(appOptions, 'app');
const { message, senderId, receiverUid } = snap.val();
console.log(message, senderId, receiverUid);
console.log('------------------------');
const deleteApp = () => adminApp.delete().catch(() => null);
try {
const db = adminApp.database();
const reciverUserRef = await db.ref(`users/${receiverUid}/contacts/${senderId}/`);
console.log('reciverUserRef', reciverUserRef);
const deviceTokenSnapshot = await reciverUserRef.child('deviceToken').once('value');
const deviceToken = await deviceTokenSnapshot.val();
console.log('deviceToken', deviceToken);
const payload = {
notification: {
title: 'Test Notification Title',
body: message,
sound: 'default',
badge: '1'
}
};
const messageDone = await admin.messaging().sendToDevice(deviceToken, payload);
console.log('Successfully sent message: ', JSON.stringify(messageDone));
return deleteApp().then(() => res);
} catch (err) {
console.log('error', err);
return deleteApp().then(() => Promise.reject(err));
}
});
Update1: According to this https://firebase.google.com/docs/cloud-messaging/send-message#send_to_a_topic, admin.messaging().sendToDevice(deviceToken, payload) APIs are only available in the Admin Node.js SDK?
So switched to
const payload = {
data: {
title: 'Test Notification Title',
body: message,
sound: 'default',
badge: '1'
},
token: deviceToken
};
const messageDone = await admin.messaging().send(payload);
Which is not working either. Getting an error Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services. Any lead will be helpful.
EDIT: Finally got the function working.
My index.js is exporting to functions, follwoing
exports.app = functions.https.onRequest(app); //React SSR
exports.updateChat = functions.database.ref('/chats/{chatId}/{messageId}').onCreate(updateChat);
exports.app is a react ssr function, which I am using to host my site. This uses database too. and throwing error of multiple database instance.
When I comment out one by one and deploy, works perfectly. But when I deploy together doesn't work. How do I separate these two keeping both at the same repo? Any suggestions, please?
You can initialise db outside export function.
const admin = require('firebase-admin');
const adminApp = admin.initializeApp(appOptions, 'app')
//continue code
Update:
const admin = require('firebase-admin');
const adminApp = admin.initializeApp(options);
async function initialize(options, apps = 'app') {
try {
const defaultApp = adminApp.name
if(defaultApp) {
const adminApp1 = admin.initializeApp(apps);
}else {
const adminApp1 = admin.initializeApp(options, apps);
}
}catch(err) {
console.error(err);
}
}
Modify this snippet as per your need and try it out
It abstracts initialize of app in another function. Just call this function at appropriate place in your code.

Categories

Resources