My error code after calling the below (which is shortened for brevity) within a cloud functions is:
Error: 3 INVALID_ARGUMENT: Location 'europe-west1' is not a valid location. Use ListLocations to list valid locations.
If I change to location to "us-central" for example, the error code changes to:
Error: 3 INVALID_ARGUMENT: Location must equal europe-west1 because the App Engine app that is associated with this project is located in europe-west1
I have had a look on stackoverflow for similar but came up short. I left a comment on this question to see if the op had any luck:
Google Cloud Tasks: Location 'europe-west1' is not a valid location
Where am I going wrong?
Thanks!
JT
OS: Google Cloud Functions
Node.js version: 12
npm version: 6.14.10
#google-cloud/tasks version: 2.3.0
Steps to reproduce
const functions = require('firebase-functions');
const {CloudTasksClient} = require("#google-cloud/tasks");
const admin = require('firebase-admin');
const client = new CloudTasksClient({ fallback: true });
// Omit the actual triggered function
async function createHttpTasks(session) {
const project = "XXXXX"; // These match my project and queue id/name
const queue = "XXXXXX";
const location = "europe-west1";
// Construct the fully qualified queue name.
const parent = client.queuePath(project, location, queue);
// Do stuff
const requestCheck = {parent, taskCheckIn};
await client.createTask(requestCheck);
}
I had two things wrong:
const client = new CloudTasksClient({ fallback: true });
should have been:
const client = new CloudTasksClient();
and
const requestCheck = {parent, taskCheckIn};
should have been
const requestCheck = {parent, task: taskCheckIn};
thanks to the gcloud team for responding to my issue:
https://github.com/googleapis/nodejs-tasks/issues/509
If anyone else is getting this error, make sure there are no spaces in the location variable. For example, there is a space at the end of the variable:
location="europe-west-3 "
Related
when i tried to deployed the cloud functions. i am facing the error below..
before update the node version it was working fine
node#14
firebase cli up-to date
nom also up-to date
const functions = require('firebase-functions')
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const cors = require('cors')({ origin: true });
admin.initializeApp()
exports.sendcertificate = functions.firestore.document('certificate/{docId}')
.onCreate((snap: { data: () => any; }, ctx: any) => {
const data = snap.data();
let authData = nodemailer.createTransport({
host: 'mail.bacttraining.com',
port: 465,
secure: true, // use SSL
auth: {
user: *******',
pass: *******',
},
});
authData.sendMail({
from: ********,
to: *********,
Bcc: '*******',
sender: "*******",
subject: "Certificate Request",
text: `${data.course}`,
html: *******,
}).then(console.log("email send sussfully"))
.catch(console.error('we cant send email : ', console.error()
));
}
);**strong text**
Make sure your CLI tools are up to date, and that your modules in use are the latest. I can see that the console is warning you that cloud functions are outdated.
Then ensure all functions that did not deploy for any bugs and syntax errors as the cloud functions uploader can crash if the code was packed incorrectly.
Once the above has been done, you can try deploying the functions one at a time with
firebase deploy --only functions:functionName
This will narrow any functions that have bugs or syntax errors down.
This issue occurs when there is difference in the node version you have installed in the system and the node engine version mentioned in package.json file.
Please check your node version using
node -v
Make sure you have mentioned the same engine version in package.json
According to the following google I/O (2019) post of the firebase team the new emulator allows us to combine firebase/database plus cloud function to fully simulate our firebase server codes. That should also mean we should be able to write tests for it.
we’re releasing a brand new Cloud Functions emulator that can also
communicate with the Cloud Firestore emulator. So if you want to build
a function that triggers upon a Firestore document update and writes
data back to the database you can code and test that entire flow
locally on your laptop (Source: Firebase Blog Entry)
I could find multiple resources looking/describing each individual simulation, but no all together
Unit Testing Cloud Function
Emulate Database writes
Emulate Firestore writes
To setup a test environment for cloud functions that allows you to simulate read/write and setup test data you have to do the following. Keep in mind, this really simulated/triggers cloud functions. So after you write into firestore, you need to wait a bit until the cloud function is done writing/processing, before you can read the assert the data.
An example repo with the code below can be found here: https://github.com/BrandiATMuhkuh/jaipuna-42-firebase-emulator .
Preconditions
I assume at this point you have a firebase project set up, with a functions folder and index.js in it. The tests will later be inside the functions/test folder. If you don't have project setup use firebase init to setup a project.
Install Dependencies
First add/install the following dependencies: mocha, #firebase/rules-unit-testing, firebase-functions-test, firebase-functions, firebase-admin, firebase-tools into the functions/package.json NOT the root folder.
cd "YOUR-LOCAL-EMULATOR"/functions (for example cd C:\Users\User\Documents\FirebaseLocal\functions)
npm install --save-dev mocha
npm install --save-dev firebase-functions-test
npm install --save-dev #firebase/rules-unit-testing
npm install firebase-admin
npm install firebase-tools
Replace all jaipuna-42-firebase-emulator names
It's very important that you use your own project-id. It must be the project-id of your own project and must exists. Fake ids won't work. So search for all jaipuna-42-firebase-emulator in the code below and replace it with your project-id.
index.js for an example cloud function
// functions/index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
// init the database
admin.initializeApp(functions.config().firebase);
let fsDB = admin.firestore();
const heartOfGoldRef = admin
.firestore()
.collection("spaceShip")
.doc("Heart-of-Gold");
exports.addCrewMemeber = functions.firestore.document("characters/{characterId}").onCreate(async (snap, context) => {
console.log("characters", snap.id);
// before doing anything we need to make sure no other cloud function worked on the assignment already
// don't forget, cloud functions promise an "at least once" approache. So it could be multiple
// cloud functions work on it. (FYI: this is called "idempotent")
return fsDB.runTransaction(async t => {
// Let's load the current character and the ship
const [characterSnap, shipSnap] = await t.getAll(snap.ref, heartOfGoldRef);
// Let's get the data
const character = characterSnap.data();
const ship = shipSnap.data();
// set the crew members and count
ship.crew = [...ship.crew, context.params.characterId];
ship.crewCount = ship.crewCount + 1;
// update character space status
character.inSpace = true;
// let's save to the DB
await Promise.all([t.set(snap.ref, character), t.set(heartOfGoldRef, ship)]);
});
});
mocha test file index.test.js
// functions/test/index.test.js
// START with: yarn firebase emulators:exec "yarn test --exit"
// important, project ID must be the same as we currently test
// At the top of test/index.test.js
require("firebase-functions-test")();
const assert = require("assert");
const firebase = require("#firebase/testing");
// must be the same as the project ID of the current firebase project.
// I belive this is mostly because the AUTH system still has to connect to firebase (googles servers)
const projectId = "jaipuna-42-firebase-emulator";
const admin = firebase.initializeAdminApp({ projectId });
beforeEach(async function() {
this.timeout(0);
await firebase.clearFirestoreData({ projectId });
});
async function snooz(time = 3000) {
return new Promise(resolve => {
setTimeout(e => {
resolve();
}, time);
});
}
it("Add Crew Members", async function() {
this.timeout(0);
const heartOfGold = admin
.firestore()
.collection("spaceShip")
.doc("Heart-of-Gold");
const trillianRef = admin
.firestore()
.collection("characters")
.doc("Trillian");
// init crew members of the Heart of Gold
await heartOfGold.set({
crew: [],
crewCount: 0,
});
// save the character Trillian to the DB
const trillianData = { name: "Trillian", inSpace: false };
await trillianRef.set(trillianData);
// wait until the CF is done.
await snooz();
// check if the crew size has change
const heart = await heartOfGold.get();
const trillian = await trillianRef.get();
console.log("heart", heart.data());
console.log("trillian", trillian.data());
// at this point the Heart of Gold has one crew member and trillian is in space
assert.deepStrictEqual(heart.data().crewCount, 1, "Crew Members");
assert.deepStrictEqual(trillian.data().inSpace, true, "In Space");
});
run the test
To run the tests and emulator in one go, we navigate into the functions folder and write yarn firebase emulators:exec "yarn test --exit". This command can also be used in your CI pipeline. Or you can use npm test instead.
If it all worked, you should see the following output
√ Add Crew Members (5413ms)
1 passing (8S)
For anyone struggling with testing firestore triggers, I've made an example repository that will hopefully help other people.
https://github.com/benwinding/example-jest-firestore-triggers
It uses jest and the local firebase emulator.
I am trying to access multiple firebase database instance in Angular WebApp. Here is my code:
firebase.database("https://<url for secondary db instance>")
I am getting the error saying:
database only accepts "app" as a parameter in database(app:App)
But in firebase documentation it says that: firebase.database('https://<url for secondary db instance>');. Here is the reference of documentation.
In package.json version firebase version ^5.0.4
Any idea what could be wrong?
Looking at the reference doc here, firebase.database() only accepts an app instance, not a string. I put in a fix for the docs that should roll out shortly. Here's the correct way to do this in JavaScript:
// init
const app1 = firebase.initializeApp({
databaseURL: "https://testapp-1234-1.firebaseio.com"
});
const app2 = firebase.initializeApp({
databaseURL: "https://testapp-1234-2.firebaseio.com"
}, 'app2');
// Get the default database instance for an app1
const database1 = firebase.database();
// Get a database instance for app2
const database2 = firebase.database(app2);
// This also works obviously
// const database1 = firebase.database(app1);
I am trying to test using firebase-functions-test. I'm wondering if I've done something wrong in the setup, because I've noticed that my function stops after trying to access the database.
const config = {
databaseURL: '******,
projectId: '*****'
};
const test = require('firebase-functions-test')(config, './devKey.json');
const myFunctions = require('../index.js');
const wrapped = test.wrap(myFunctions.search.fetchProfiles);
let before = test.database.makeDataSnapshot('', 'cloud-functions/fetchProfiles/
-L8eDyqVjH2WcsnfFDj3/request');
let after = test.database.makeDataSnapshot({
version: '1.0.8',
userIds: ['-L4dcm7BSctgsqAzpeOP']
}, 'cloud-functions/fetchProfiles/-L8eDyqVjH2WcsnfFDj3/request' );
let change = test.makeChange(before, after);
let context = {
params: {userId: '-L8eDyqVjH2WcsnfFDj3'}
};
wrapped(change, context);
Then, when this line of code is ran within the function:
data.after.ref.parent.child('state').once('value')
It is not successful. The function has no problems when deployed. In particular, are my data snapshots created properly?
This was fixed in version 0.1.1 of firebase-functions-test.
I have no idea why, but it's 3 weeks later now and I tried it, and now it works. I don't recall changing anything.
Follow the guide of using Cloud Functions with Firebase.
Setup environment
setup project in Firebase
Created function
command prompt writes that function deployed, but firebase is empty.
I am new with deploying functions so I am sure that it is stupid question and I think I did something wrong in setting up but I checked three times different guides and it looks everything done right. So please if you know what the problem it is can be?
I used this guide and there I done everything till initializing the project
https://firebase.google.com/docs/functions/get-started
After that in index.js I wrote a function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(function.config().firebase);
export.sendNotification = functions.database
.ref('/notifications/{user_id}/{notification_id}')
.onWrite(event => {
conts user_id = event.params.user_id;
const notification = event.params.notification_id;
if(!event.data.val()){
return console.log('A notification has been deleted ', notification_id);
}
const payload = {
notification: {
title: "Friend Request",
body: "Received new Friend Request",
icon: "default"
}
};
return admin.messaging().sendToDevice(/*Token*/, payload).then(response =>{
console.log('');
});
});
And with the command
firebase deploy
I tried to deploy function
But in firebase cattegory "Function" it is still empty
Error in CMD
There is syntax error, Please change below line in your code
admin.initializeApp(function.config().firebase);
to
admin.initializeApp(functions.config().firebase);
I'm quite late here but it might help somebody else. You're right, it is typo. The correct command is:
exports
not
export